How to multiple a number by 2 (double)present in a particular line number of a file, in Linux?



Name: John Smith
Grade: 8
Institute: Baldwin
Number of entries: 125
State: Texas


Name: David Buck
Grade: 9
Institute: High Prime
Number of entries: 123
State: California

There are many such similar files in which the Number of entries (present at line number 4 in all files) has to doubled.

For File_A it should be 250 and for File_B 246.

How to do this for all files in Linux?(using sed or awk or any other commands)

Tried commands:

sed -i '4s/$2/$2*2/g' *.txt               (nothing happening from this)
awk "FNR==4 {sub($2,$2*2)}" *.txt         (getting syntax error)


Thank you for all the answers.
With your help I was able to figure out simple solution by understanding and combining your answers.

Here it is (which worked in my environment):

To display on terminal:
awk 'FNR==4 {sub($4,$4*2)} 1' File_A

To move to some file:
awk 'FNR==4 {sub($4,$4*2)} 1' File_A > temp_A

To perform changes inside file using inplace:
awk -i inplace 'FNR==4 {sub($4,$4*2)} 1' *.txt

$4 being 4th parameter in the line;
FNR==4 being the line number 4;
1 at the end helps in printing everything

Answered By – John809

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published