0
votes

I have a text file as shown below. I would like to subtract the numbers in the first column and add a new column with the calculated values(absolute value) to the input files instead of printing the output. How can I do this for multiple files with awk or sed?

46-104   46   3.95073
46-46    46   1.45997
50-50    50   1.51589
52-100   52   4.16567

desired output

46-104   46   3.95073   58
46-46    46   1.45997   0
50-50    50   1.51589   0
52-100   52   4.16567   48
3

3 Answers

2
votes

Here's the quick way using awk:

awk '{ split($1,a,"-"); print $0, (a[1]-a[2] >= 0 ? a[1]-a[2] : a[2]-a[1]) | "column -t" }' file

Results:

46-104  46  3.95073  58
46-46   46  1.45997  0
50-50   50  1.51589  0
52-100  52  4.16567  48

For multiple files, assuming you only have files of interest in your present working directory:

for i in *; do awk '{ split($1,a,"-"); print $0, (a[1]-a[2] >= 0 ? a[1]-a[2] : a[2]-a[1]) | "column -t" }' "$i" > "$i.temp" && mv "$i.temp" "$i"; done
0
votes

With awk:

function abs(value)
{
    return (value<0?-value:value);
}

{
    split($1, v, "-")        
    print $0, "\t", abs(v[1]-v[2])
}

Online demo

0
votes

This might work for you (GNU sed and bc):

sed -r 'h;s/(\S+).*/echo \1|bc/e;H;x;s/\n-?/ /' file
  • h copy the line to the hold space (HS)
  • s/(\S+).*/echo \1|bc/e do the maths in the pattern space
  • H append a newline and the answer to the original line in the HS
  • x swap PS and HS
  • s/\n-?/ / substitute the newline and any negative symbol with a space

Along the same lines using awk:

 awk '{split($1,a,"-");b=a[1]-a[2];sub(/-/,"",b);print $0,b}' file