change value to negative

How to change value in column 5 to negative based on value in column 2 ?
Example: For all records with A in column 2 change value in column 5 to negative.

file
Code:
1234~A~b~c~10~e~f~g~h~09/10/09
1234~A~b~c~75~e~f~g~h~11/12/10
1234~A~b~c~40~e~f~g~h~12/06/10
5678~B~b~c~2~e~f~g~h~01/11/11
5678~B~b~c~6~e~f~g~h~03/28/13
8910~A~b~c~80~e~f~g~h~07/29/11
1023~B~b~c~15~e~f~g~h~10/22/09
1023~B~b~c~22~e~f~g~h~04/22/14

desired output
Code:
1234~A~b~c~-10~e~f~g~h~09/10/09
1234~A~b~c~-75~e~f~g~h~11/12/10
1234~A~b~c~-40~e~f~g~h~12/06/10
5678~B~b~c~2~e~f~g~h~01/11/11
5678~B~b~c~6~e~f~g~h~03/28/13
8910~A~b~c~-80~e~f~g~h~07/29/11
1023~B~b~c~15~e~f~g~h~10/22/09
1023~B~b~c~22~e~f~g~h~04/22/14

awk -F '~' ' BEGIN {OFS="~"}
          {
          if($2=="A") 
             { $5*=-1}
          print $0
          }  ' inputfile  > outputfile

Hi,

Using Perl:

$ cat infile
1234~A~b~c~10~e~f~g~h~09/10/09
1234~A~b~c~75~e~f~g~h~11/12/10
1234~A~b~c~40~e~f~g~h~12/06/10
5678~B~b~c~2~e~f~g~h~01/11/11
5678~B~b~c~6~e~f~g~h~03/28/13
8910~A~b~c~80~e~f~g~h~07/29/11
1023~B~b~c~15~e~f~g~h~10/22/09
1023~B~b~c~22~e~f~g~h~04/22/14
$ perl -F"~" -lane 'printf "%s\n", join "~", @F[0..3], $F[1] eq "A" ? $F[4]*-1 : $F[4], @F[5..$#F]' infile 
1234~A~b~c~-10~e~f~g~h~09/10/09
1234~A~b~c~-75~e~f~g~h~11/12/10
1234~A~b~c~-40~e~f~g~h~12/06/10
5678~B~b~c~2~e~f~g~h~01/11/11
5678~B~b~c~6~e~f~g~h~03/28/13
8910~A~b~c~-80~e~f~g~h~07/29/11
1023~B~b~c~15~e~f~g~h~10/22/09
1023~B~b~c~22~e~f~g~h~04/22/14

Regards,
Birei

for the awk code
Thanks for quick reply
2 issues:

1)It made 0 into -0 which create and issue to process file
2) It is rounding the numbers. Can we keep the number or round to 2 decimals at least?

that is all

thanks again

kent$  cat a.tmp
1023~B~b~c~22~e~f~g~h~04/22/14
8910~A~b~c~0~e~f~g~h~07/29/11
8910~A~b~c~10.23448~e~f~g~h~07/29/11



kent$  awk -F'~' 'BEGIN{OFS="~"}$2=="A"{$5=($5==0)?$5:"-"$5}1' a.tmp
1023~B~b~c~22~e~f~g~h~04/22/14
8910~A~b~c~0~e~f~g~h~07/29/11
8910~A~b~c~-10.23448~e~f~g~h~07/29/11

Or: [note, this rounds the numbers]

kent$  awk -F'~' 'BEGIN{OFS="~"}$2=="A"{$5=-$5}1' a.tmp                                                                                  
1023~B~b~c~22~e~f~g~h~04/22/14
8910~A~b~c~0~e~f~g~h~07/29/11
8910~A~b~c~-10.2345~e~f~g~h~07/29/11

1 Like