1

How can i add a different value to each column in a bash script?

Example: Three function f1(x) f2(x) f3(x) plotted over x

test.dat:

# x  f1    f2    f3 
1    0.1  0.01  0.001
2    0.2  0.02  0.002
3    0.3  0.03  0.003

Now i want to add to each function a different offset value

values = 1 2 3

Desired result:

# x  f1    f2    f3 
1    1.1  2.01  3.001
2    1.2  2.02  3.002
3    1.3  2.03  3.003

So first column should be unaffected, otherwise the value added.

I tried this, but it doesn work

declare -a energy_array=( 1 2 3 )

for (( i =0 ; i <  ${#energy_array[@]} ; i ++ ))
do
local energy=${energy_array[${i}]}
cat "test.dat" \
 | awk -v "offset=${energy}" \ 
'{ for(j=2; j<NF;j++) printf "%s",$j+offset OFS; if (NF) printf "%s",$NF; printf ORS} '
done 

1 Answer 1

5

You can try the following:

declare -a energy_array=( 1 2 3 )
awk -voffset="${energy_array[*]}" \
'BEGIN { n=split(offset,a) } 
 NR> 1{ 
   for(j=2; j<=NF;j++) 
      $j=$j+a[j-1]
   print;next
 }1' test.dat

With output:

# x  f1    f2    f3 
1 1.1 2.01 3.001
2 1.2 2.02 3.002
3 1.3 2.03 3.003
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.