1

I have a comma delimited text file on a Linux machine. First I want to match col1 with col4 and col5, if col1 matches with col4 then print all values from col4 in all rows where col1 is empty and if if col1 matches with col5 print all values from column 5 in all rows where col1 is empty until a new value appears in column1. Input file:

va,group,subgroup,minor,major 
A,AGT,rs123,A,G
 ,AGT,rs456,G,T
 ,AGT,rs457,T,G
 ,AGT,rs667,A,T
G,GSTT1,rs234,A,G
 ,GSTT1,rs668,T,G
 ,GSTT1,rs556,A,G

Expected output:

va,group,subgroup,minor,major 
A,AGT,rs123,A,G
G,AGT,rs456,G,T
T,AGT,rs457,T,G
A,AGT,rs667,A,T
G,GSTT1,rs234,A,G
G,GSTT1,rs668,T,G
G,GSTT1,rs556,A,G

This is what I tried:

if [ $1 == $4] && [ -z "$1" ]
then
   awk -F"\t -v OFS="\t" '{ for(N=1; N<=NF; N++) if($N=="") $N=$4 } 1' file > tmp1
else
  echo "stop"
fi
2
  • 1
    what if both col4 and col5 match? what if $1 is empty in the first line?
    – pLumo
    Dec 7, 2021 at 12:05
  • Please edit your question and clarify the logic. When should we populate column 1 with the value of column 4 and when should we use the value of column 5?
    – terdon
    Dec 7, 2021 at 13:35

1 Answer 1

2

You could use something like this:

awk '
  BEGIN{FS=OFS=","; c=1}
  $1==" "{$1=$c;print;next}
  {c=1}
  $1==$4{c=4}
  $1==$5{c=5}1
' file
  • If both $4 and $5 match, this will give precedence to the last one (here: $5).
  • If first row is empty or neither $4 nor $5 match, c will be set to 1.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .