Reputation: 13
How can i change the 2nd column from positive to negative and vice versa
aa.txt
31OCT2013:00:00:00,220.10,"O","090500 13549951"
31OCT2013:00:00:00,-0.32,"I","090500 13549964"
Answer should be
aa.txt
31OCT2013:00:00:00,-220.10,"O","090500 13549951"
31OCT2013:00:00:00,+0.32,"I","090500 13549964"
If i use awk
'BEGIN{FS=OFS=","} {$2=-$2}1' aa.txt
the result is
1OCT2013:00:00:00,-220.1,"O","090500 13549951"
31OCT2013:00:00:00,+0.32,"I","090500 13549964"
In the first result, sign is changing but 0 is missing, instead of -220.10
, it is showing as -220.1
.
Upvotes: 1
Views: 1154
Reputation: 10039
sed 's/^\([^,]*,\)-/\1/
t
s/^[^,]*,/&-/' YourFile
Based on -
existance
Upvotes: 1
Reputation: 1842
Use sprintf to format the output.
awk 'BEGIN{FS=OFS=","} {$2=sprintf("%+.2f",-$2)}1' aa.txt
Upvotes: 0
Reputation: 289585
Considering you want to change the second column based on comma, this can be a way:
$ awk 'BEGIN{FS=OFS=","} {$2=-$2}1' aa.txt
31OCT2013:00:00:00,-220.1,"O","090500 13549951"
31OCT2013:00:00:00,0.32,"I","090500 13549964"
See
31OCT2013:00:00:00,-220.1,"O","090500 13549951"
^
31OCT2013:00:00:00,0.32,"I","090500 13549964"
^
With the previous version we were losing trailing zeros, as per a arithmetic behaviour. To handle it properly, we can do:
awk 'BEGIN{FS=OFS=","} {if ($2>0) $2="-"$2; else sub("-", "", $2)}1' file
In case the value is positive, it adds a dash in front of the string. Otherwise, it just deletes the dash.
Given a sample file
$ cat a
31OCT2013:00:00:00,220.10,"O","090500 13549951"
31OCT2013:00:00:00,-0.32,"I","090500 13549964"
31OCT2013:00:00:00,0.300,"I","090500 13549964"
31OCT2013:00:00:00,-0.300,"I","090500 13549964"
31OCT2013:00:00:00,0,"I","090500 13549964"
It returns
$ awk 'BEGIN{FS=OFS=","} {if ($2>0) $2="-"$2; else sub("-", "", $2)}1' a
31OCT2013:00:00:00,-220.10,"O","090500 13549951"
31OCT2013:00:00:00,0.32,"I","090500 13549964"
31OCT2013:00:00:00,-0.300,"I","090500 13549964"
31OCT2013:00:00:00,0.300,"I","090500 13549964"
31OCT2013:00:00:00,0,"I","090500 13549964
Upvotes: 0