简体   繁体   中英

Bash - How to increase positive numbers by constant and decrease negative ones by same constant? (Awk/sed probably)

I have a multiple files of numbers like:

file1.txt

 0.77031
-10.25150   2.80417   3.62904  -9.72425   1.41742   7.96870
-24.75966
-11.22983   21.17503  -0.74532
-13.55239

I need to change every positive number by +x and every negative one by -x. Lets have x=8

I tried awk script for this:

for a in $@; do
awk '{FS=OFS="." }/-/{$1-=16}1' $a | awk '{FS=OFS="." }/\d*/{$1+=8}1'
done 

but it seems to work only on first number in line. How to make it work for all numbers in line?

Wanted output:

 8.77031
-18.25150   10.80417   11.62904  -17.72425   9.41742   15.96870
-32.75966
-19.22983   29.17503  -8.74532
-21.55239

I thought about using sed, but it seems to not work well for increasing and deceasing numbers

$ awk -v n=8 '{for (i=1; i<=NF; i++) $i += ($i<0 ? -n : n)} 1' file
8.77031
-18.2515 10.8042 11.629 -17.7242 9.41742 15.9687
-32.7597
-19.2298 29.175 -8.74532
-21.5524

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM