我想从另一个文件中按顺序替换与一个文件中的模式匹配的行,例如,给定:
文件1.txt:
aaaaaa
bbbbbb
!! 1234
!! 4567
ccccc
ddddd
!! 1111
我们喜欢替换以 !! 开头的行与此文件的行:
文件2.txt:
first line
second line
third line
所以结果应该是:
aaaaaa
bbbbbb
first line
second line
ccccc
ddddd
third line
答案1
可以轻松完成awk
awk '
/^!!/{ #for line stared with `!!`
getline <"file2.txt" #read 1 line from outer file into $0
}
1 #alias for `print $0`
' file1.txt
其他版本
awk '
NR == FNR{ #for lines in first file
S[NR] = $0 #put line in array `S` with row number as index
next #starts script from the beginning
}
/^!!/{ #for line stared with `!!`
$0=S[++count] #replace line by corresponded array element
}
1 #alias for `print $0`
' file2.txt file1.txt
答案2
与GNU sed
, 类似于awk+getline
$ sed -e '/^!!/{R file2.txt' -e 'd}' file1.txt
aaaaaa
bbbbbb
first line
second line
ccccc
ddddd
third line
R
一次给出一行- 顺序很重要,先
R
在后d
和perl
$ < file2.txt perl -pe '$_ = <STDIN> if /^!!/' file1.txt
aaaaaa
bbbbbb
first line
second line
ccccc
ddddd
third line
- 将带有替换行的文件作为标准输入传递,以便我们可以使用
<STDIN>
filehandle读取它 - 如果找到匹配的行,则替换
$_
为标准输入中的行