Raj
Raj

Reputation: 19

Search for a pattern and replace entire column with searched pattern in a pipe delimited file

I have pipe delimited file with 30 columns and this may change. .I need to search for certain pattern on all columns and when match is found I need to replace entire column with matched pattern.Here is the example

Id|col1|col2|col3
20|eff ghb abcxrar Kano|abcrar|thgh abctgggrar 
30|abcrar|fgt Lon abcfgtrar|abctrar def

Need to search for string that starts with abc and finishes with rar and replace entire column with it when matched Output should be :

Id|col1|col2|col3
20|abcxrar|abcrar|abctgggrar
30|abcrar|abcfgtrar|abctrar

Upvotes: 1

Views: 49

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133538

Following awk may help you on same:

awk -F"|" '{for(i=1;i<=NF;i++){num=split($i,array," ");for(j=1;j<=num;j++){if(match(array[j],/^abc.*rar$/)){$i=substr(array[j],RSTART,RLENGTH)}}}} 1' OFS="|"  Input_file

Adding a non one liner form of solution too now:

awk -F"|" '
{
  for(i=1;i<=NF;i++){
    num=split($i,array," ");
    for(j=1;j<=num;j++){
      if(match(array[j],/^abc.*rar$/)){
        $i=substr(array[j],RSTART,RLENGTH)}}}
}
1' OFS="|"  Input_file

Output will be as follows:

Id|col1|col2|col3
20|abcxrar|abcrar|abctgggrar
30|abcrar|abcfgtrar|abctrar

Upvotes: 1

Related Questions