Abdel
Abdel

Reputation: 6106

Unix code wanted to change column values

I have a file that looks like this:

ID1 ID2 3
ID2 ID3 3
ID4 ID5 3
ID6 ID7 4
ID8 ID9 4
ID8 ID6 4

And I want to change it to:

ID1 ID2 1
ID2 ID3 1
ID4 ID5 1
ID6 ID7 2
ID8 ID9 2
ID8 ID6 2

So I want to change all 3's and 4's from the third column to 1's and 2's respectively. What is the most efficient way to do this for a very large file? Many thanks in advance!

Upvotes: 4

Views: 5187

Answers (2)

aland
aland

Reputation: 5154

Assuming third column is always the last one:

sed 's/\([^0-9]\)3$/\11/;s/\([^0-9]\)4$/\12/'

Upvotes: 1

Mark Reed
Mark Reed

Reputation: 95242

awk '{ $3 -= 2; print }' filename >new_filename 

Or, if you really only want to touch 3's and 4's:

awk '{ if ( $3 == 3 ) { $3 = 1 } else if ( $3 == 4 ) { $3 = 2 }; print}' filename >new_filename

Upvotes: 6

Related Questions