2

In the data given below (which is tab separated):

# data
1  xyz   alfa  x=abc;z=cbe;d=fed  xt
2  xyz   alfa  y=cde;z=xy  ft
3  xyb   delta xy=def  zf

I want to add a suffix _LT in the elements (values of the variables) of 4th column after splitting at ;.

Output like:

1  xyz   alfa  x=abc_LT;z=cbe_LT;d=fed_LT  xt
2  xyz   alfa  y=cde_LT;z=xy_LT  ft

I am able to add suffix at specific columns, but can't split(at delim)-add-merge.

awk -v  PRE='_LT' '{$4=$4PRE; print}' OFS="\t" data.txt > data_LT.txt
everestial007
  • 6,665
  • 7
  • 32
  • 72

3 Answers3

3

you can use split function, loop and merge... or use substitutions

$ awk -v PRE='_LT' '{gsub(/;/,PRE";",$4); sub(/$/,PRE,$4); print}' OFS='\t' data.txt
1   xyz alfa    x=abc_LT;z=cbe_LT;d=fed_LT  xt
2   xyz alfa    y=cde_LT;z=xy_LT    ft
3   xyb delta   xy=def_LT   zf
  • gsub(/;/,PRE";",$4) replace all ; with _LT; only for 4th column
  • sub(/$/,PRE,$4) append _LT to 4th column
Sundeep
  • 23,246
  • 2
  • 28
  • 103
1

Another thought is to use split() in awk,

awk -v PRE='_LT' '{ 
    n=split($4,a,/;/); 
    b=""; 
    for(i in a){ b=b a[i] PRE; if(i!=n){b=b";"} }
    {$4=b; print $0}
}' OFS='\t' data.txt

n=split($4,a,/;/) splits $4 using the separator ';'. And print the split result as your desired.

CWLiu
  • 3,913
  • 1
  • 10
  • 14
0

Using Perl

$ cat everestial
1  xyz   alfa  x=abc;z=cbe;d=fed  xt
2  xyz   alfa  y=cde;z=xy  ft
3  xyb   delta xy=def  zf

$ perl -F'/\s+/' -lane ' $F[3]=~s/(.+?)=(.+?)\b/${1}=${2}_LT/g; print join("\t",@F) ' everestial
1       xyz     alfa    x=abc_LT;z=cbe_LT;d=fed_LT      xt
2       xyz     alfa    y=cde_LT;z=xy_LT        ft
3       xyb     delta   xy=def_LT       zf
stack0114106
  • 8,534
  • 3
  • 13
  • 38