I want to subtract the values from two columms and add result into a new column (at the very end) using awk or bash. the data is in a txt file.
I tried awk 'BEGIN {OFS="\t"} NR == 1 {$20 = "tr_pe"} NR >=2 {$20= $5-$11}1' <filename
or awk OFS="\t" \{$(NF 1)=$5-$11}1' filename.txt
The first code did the subtraction but saved it in column 2 instead of at the end, and i realised that it actually did not get saved to the txt.file. Second one did some calculation but it was not accurate
What i want to do - subtract values from Column 5 with Column 11 and save it under header tr_pre (which falls into column 20 at the end of all the 19 columns in the file). Columns seperated by tab.
CodePudding user response:
You could use next after line 1 to continue the iteration. To print the result at the end, you can print the whole line using $0
followed by the value that you want at the end.
cat filename.txt
c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 c16 c17 c18 c19
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
For example
awk 'BEGIN {OFS="\t"}
{$1=$1}
NR == 1 {
print $0, "tr_pre"
next
}
{
print $0, $5-$11
}' filename.txt > output.txt
output.txt
c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 c16 c17 c18 c19 tr_pre
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 -6
CodePudding user response:
Based on your description, this should solve your problem.
awk 'BEGIN {FS=OFS="\t"} NR == 1 {print $0, "tr_pre"} NR >=2 {print $0, $5 - $11}' filename.tsv > file_with_new_tr_pre_column.tsv
If there are other confounding factors, please provide a minimal reproducible example