user3034987
user3034987

Reputation: 97

In place string replacement of file in linux

I Am trying to Read a file in linux line by line containg data something like this

522240227       B009CPMJ1M      20141003        20141103        1063278  1       1       6
604710621       B004NPI3OI      20141003        20141103        166431   1       1       6
1498812521      B00LFEHWJM      20141003        20141103        1044646  1       10      6
1498812521      B00D3IK0Y2      20141003        20141103        1044646  2       10      6

I then have to add 2000000000 to the first integer of each line and replace that integer. So final File would be like

2522240227       B009CPMJ1M      20141003        20141103        1063278  1       1       6
2604710621       B004NPI3OI      20141003        20141103        166431   1       1       6
31498812521      B00LFEHWJM      20141003        20141103        1044646  1       10      6
31498812521      B00D3IK0Y2      20141003        20141103        1044646  2       10      6

Is there i can do this operation on the same file without creating any other temporary file using shell script

Upvotes: 0

Views: 70

Answers (1)

fedorqui
fedorqui

Reputation: 289555

This is for awk!

awk '{$1+=2000000000}1' file

It returns:

2522240227 B009CPMJ1M 20141003 20141103 1063278 1 1 6
2604710621 B004NPI3OI 20141003 20141103 166431 1 1 6
3498812521 B00LFEHWJM 20141003 20141103 1044646 1 10 6
3498812521 B00D3IK0Y2 20141003 20141103 1044646 2 10 6

It is quite explanatory: $1+=2000000000 adds 2000000000 to the first value. Then, 1 is True, so it performs the default awk action: {print $0}, that is, print the line.

To replace the file, redirect to a temp file and then move:

awk '{$1+=2000000000}1' file > new_file && mv new_file file

Since it was a big number and it was printing in a e+xx format, let's fix the format with sprintf():

awk '{$1 = sprintf("%0.f", $1+=2000000000)}1' file

This takes profit of the sprintf to store a formated value into a variable, so that then it is printed properly.

Upvotes: 1

Related Questions