user3206886
user3206886

Reputation: 39

awk/sed convert positive value to negative in a semicolon separated file

I have a file which is built up like this:

1233;mc3; limit;1
946;mc3; limit;14545
0843;mc3; limit;2
443;mc3;Short  ;1012
1309;mc3;Short  ;1
1247;mc3;Short  ;1121
989;mc3;Short  ;1
1340;mc3;Short  ;14545
170;mc3;Short  limit;1
105964;mc3; rep;2000000
4934;mc3; rep;1
3028;mc3; rep;14545

The only thing I know for sure is that everyhting is ';' separated.

I want to edit the value in the fourth column to a negativ value. In the file, this value will always be positive.

What I've come up with so far is this:

[usr@serv] cat list | awk -F";" '{gsub ("^","-",$4);print}'
123213 mc  limit -1
946 mc  limit -14545
08743 mc  limit -2
4493 mc Short   -1012
13009 mc Short   -1
12147 mc Short   -1121
9989 mc Short   -1
13490 mc Short   -14545
1780 mc Short  limit -1
1054964 mc  rep -2000000
49324 mc  rep -1
30828 mc  rep -14545

But as you can see it removes the ";". What am I doing wrong here?

It doesnt really matter to me if I use awk or sed, or if I edit the original file or print it to a new file. I just want to convert the value after the third ";".

Upvotes: 1

Views: 526

Answers (3)

Alex Jurado - Bitendian
Alex Jurado - Bitendian

Reputation: 1027

rev filename | sed 's/;/-;/' | rev

Upvotes: 3

Jotne
Jotne

Reputation: 41456

You are missing OFS set to ;. You can also do like this:

awk -F\; '{$4=0-$4}8' OFS=\; file
1233;mc3; limit;-1
946;mc3; limit;-14545
0843;mc3; limit;-2
443;mc3;Short  ;-1012
1309;mc3;Short  ;-1
1247;mc3;Short  ;-1121
989;mc3;Short  ;-1
1340;mc3;Short  ;-14545
170;mc3;Short  limit;-1
105964;mc3; rep;-2000000
4934;mc3; rep;-1
3028;mc3; rep;-14545

Upvotes: 2

Beta
Beta

Reputation: 99094

sed 's/\([0-9]*$\)/-\1/' filename

Upvotes: 1

Related Questions