
我想從另一個文件中按順序替換與一個文件中的模式匹配的行,例如,給定:
文件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讀取它 - 如果找到匹配的行,則替換
$_
為標準輸入中的行