DylanDog
DylanDog

Reputation: 109

Update specific line of a txt file

Using terminal, I have this output "Date.IPLOG" How can I update/add this output to a specific line of another txt overwriting only that previous line content?

output Date.IPLOG the line 5000 = IP changed Date.IPLOG

Upvotes: 1

Views: 60

Answers (1)

John1024
John1024

Reputation: 113814

Let's suppose your starting file is:

$ cat file
1
2
3
4
5

And suppose you want to change line 3 to NewValue. In that case, run:

$ awk -v new="NewValue" -v line=3 'NR==line{$0=new} 1' file
1
2
NewValue
4
5

That displays the new version to stdout. To change file, run:

awk -v new="NewValue" -v line=3 'NR==line{$0=new} 1' file >tmp && mv tmp file

Or, if you have gawk (GNU awk), we can simplify the above to:

awk -i inplace -v new="NewValue" -v line=3 'NR==line{$0=new} 1' file

How it works

  1. -v new="NewValue" creates an awk variable new.

  2. -v line=3 creates an awk variable line.

  3. If the current line number, NR, is line, then NR==line{$0=new} changes the contents of the line, $0, to new.

  4. 1 is awk's shorthand for print-the-line.

Upvotes: 1

Related Questions