Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

sed

awk

File_A

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

File_B

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)
like image 424
John809 Avatar asked Nov 21 '25 16:11

John809


1 Answers

With your shown samples please try following awk code. Simple explanation would be look/search for string /Number of entries: and then multiply 2 into value of last field and save it within itself, then print lines by mentioning 1.

awk '/Number of entries:/{$NF = ($NF * 2)} 1' File_A File_B

Run above command it will print output on screen, once you are Happy with output and want to save output into Input_file itself then you can try awk's -inplace option(available in GNU awk 4.1+ version etc).

Also if your files extension is .txt then pass it to above awk program itself, awk can read multiple files itself.

like image 151
RavinderSingh13 Avatar answered Nov 24 '25 08:11

RavinderSingh13



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!