3

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
4

3 回答 3

3

GNU sed

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

script.sed

/second textblock/{
n
r file3
q
}

-- 输出为:

第一的
文本
堵塞

第二个文本块

全部
这
其他
线条

于 2013-06-18T12:50:44.813 回答
3

一种方法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
于 2013-06-18T12:21:09.457 回答
2

这个问题是关于按段落阅读文件:

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

或者

perl -00 -pe '$.==3 and $_=`cat file2`."\n"' file1
于 2013-06-18T15:14:29.293 回答