简体   繁体   中英

Modify values of one column based on values of another column on a line-by-line basis

I'm looking to use bash/awk/sed in order to modify a document.

The document contains multiple columns. Column 5 currently has the value "A" at every row. Column six is composed of increasing numbers. I'm attempting a script that goes through the document line by line, checks the value of Column 6, if the value is greater than a certain integer (specifically 275) the value of Column 5 in that same line is changed to "B".

while IFS="" read -r line ; do
 awk 'BEGIN {FS = " "}'
 Num=$(awk '{print $6}' original.txt)
 if [ $Num > 275 ] ; then
  awk '{ gsub("A","B",$5) }'
 fi
done < original.txt >> edited.txt

For the above, I've tried setting the residueNum variable both inside and outside of the while loop.

I've also tried using a for loop and cat:

awk 'BEGIN {FS = " "}' original.txt
Num=$(awk '{print $6}' heterodimer_P49913/unrelaxed_model_1.pdb)
integer=275

for data in $Num ; do
  if [ $data > $integer ] ; then
   ##Change value in other column to "B" for all lines containing column 6 values greater than "integer"
  fi
done

Thanks in advance.

GNU AWK does not need external while loop (there is implicit loop), if you need further explanation read awk info page . Let file.txt content be

1 2 3 4 A 100
1 2 3 4 A 275
1 2 3 4 A 300

and task to be

checks the value of Column 6, if the value is greater than a certain integer (specifically 275) the value of Column 5 in that same line is changed to "B".

then it might be done using GNU AWK following way

awk '$6>275{$5="B"}{print}' file.txt

which gives output

1 2 3 4 A 100
1 2 3 4 A 275
1 2 3 4 B 300

Explanation: action set value of 5th field ( $5 ) to B is applied conditionally to rows where value of 6th field is greater than 275. Action to print is applied unconditionally to all lines. Observe that change if applied is done before print ing.

(tested in GNU Awk 5.0.1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM