TransWikia.com

Copy and paste between special lines using awk command

Ask Ubuntu Asked by nader ahmadvand on March 9, 2021

I have a problem with awk in this command

awk 'NR==1,/mode/{next}/tot/,NR==0{next}{print}' 1.out > 2.dat

From the contents of file 1, I put the lines between the line that starts with the word mode and the line that starts with the word tot in file 2.

Now I want to put this data that I am copying from file 1 in another file like file 3 (which already exists and has contents) between the lines that start with the specific words mode and tot.
Can anyone help me?

One Answer

Lets assume that the given awk command

awk 'NR==1,/mode/{next}/tot/,NR==0{next}{print}' 1.out > 2.dat

was executed, and created file 2.dat.

In order to modify an existing file 3.out as requested, here is the answer using one awk command (to create a temporary file /tmp/3.out.tmpfile):

awk 'FNR==1{nf++}; NR==1,/mode/{print;next}; f2==0{f2=1;nextfile}; nf==2{print;next}; /tot/,0{print}' 3.out 2.dat 3.out > /tmp/3.out.tmpfile

and one mv command (to replace the original 3.out file by the modified one /tmp/3.out.tmpfile):

mv /tmp/3.out.tmpfile 3.out

For example, if the original 3.out file contains:

line-1
line-2
mode
line-X
line-Y
line-Z
tot
line-3
line-4
line-5

and file 2.dat contains:

inserted-line-A
inserted-line-B
inserted-line-C
inserted-line-D
inserted-line-E

then the above proposed commands will result in a modified 3.out file that now contains:

line-1
line-2
mode
inserted-line-A
inserted-line-B
inserted-line-C
inserted-line-D
inserted-line-E
tot
line-3
line-4
line-5

The original 3.out lines between mode and tot have now been replaced by the ones in file 2.dat.

Answered by Ioannis Papadopoulos on March 9, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP