tmartin
tmartin

Reputation: 321

Replace lines by line number with lines from other file

I'm searching for an elegant way to replace a block of lines in ASCII-file1 with all lines of file2 beginning with the 2nd line. The lines to be replaced in file1 are encapsulated within blank line nr.2 and nr.3 .

The numbers of the first and the last line of the block in file1 are fix for a bunch of files, but a more general solution would be desirable.

file1:

first
text
block
                        #blank line
second textblock
                        #blank line
third
text
block
                        #blank line

file2:

first line
all
the 
other
lines

expected file1 after replacement:

first
text
block
                        #blank line
second textblock
                        #blank line
all
the 
other
lines
                        #blank line

Upvotes: 3

Views: 161

Answers (3)

glenn jackman
glenn jackman

Reputation: 246799

This question is about reading a file by paragraphs:

awk 'NR==3 {while (getline < "file2") print; next} 1' RS='' ORS='\n\n' file1

or

perl -00 -pe '$.==3 and $_=`cat file2`."\n"' file1

Upvotes: 2

captcha
captcha

Reputation: 3756

GNU sed

sed '2,$!d' file2 > file3
sed -f script.sed file1

script.sed

/second textblock/{
n
r file3
q
}

-- The output is:

first
text
block

second textblock

all
the
other
lines

Upvotes: 3

Chris Seymour
Chris Seymour

Reputation: 85785

One way with awk:

$ match="second textblock"

$ awk 'NR==FNR&&!p;$0~m{print p;p=1};NR>FNR&&FNR>1' m="$match" file1 file2
first
text
block
                     #blank line               
second textblock

all                  #blank line
the 
other
lines
                     #blank line

Upvotes: 3

Related Questions