0

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 Answers 3

2

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 
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you!! Is it possible to add the subtracted values to the input files instead of printing the output?
@user2013230: No worries! Unfortunately awk doesn't include a native means of editing a file in-place. To work around this, you'll need to use mv. Please see the edit I've made. It will work on multiple files and apply the changes. HTH.
0

With awk:

function abs(value) { return (value<0?-value:value); } { split($1, v, "-") print $0, "\t", abs(v[1]-v[2]) } 

Online demo

Comments

0

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.