Reputation:
I currently have a variable `$var1' that contains the following:
4 -38 2 -42 1 -43 10 -44 1 -45 6 -46 1 -48 1 -49
I want to add 50 and then multiply by 2 for every second number. That is,
(-38 + 50) * 2 = 24
(-42 + 50) * 2 = 16
I would then want to replace -38
with 24
and -42
with 16
. How should I go about doing this?
Would you do this with awk
? If so, how do you cycle through the each item in a single line? I see awk
can loop through rows but haven't seen an example of looping through items on a line.
Thanks for your help.
Upvotes: 0
Views: 95
Reputation: 204055
$ echo "$var1" | awk '{for (i=2;i<=NF;i+=2) $i=($i+50)*2}1'
4 24 2 16 1 14 10 12 1 10 6 8 1 4 1 2
Upvotes: 1
Reputation: 2050
Try this :
echo $var | awk -F" " '{ for (i=1; i<=NF; i++) if(i%2 == 0) printf "%d ",( $i + 50 ) * 2 ; else printf "%d ",$i }'
Upvotes: 2