![如何在文件中找到單字並在其下方插入兩行文字?](https://rvso.com/image/97225/%E5%A6%82%E4%BD%95%E5%9C%A8%E6%96%87%E4%BB%B6%E4%B8%AD%E6%89%BE%E5%88%B0%E5%96%AE%E5%AD%97%E4%B8%A6%E5%9C%A8%E5%85%B6%E4%B8%8B%E6%96%B9%E6%8F%92%E5%85%A5%E5%85%A9%E8%A1%8C%E6%96%87%E5%AD%97%EF%BC%9F.png)
我有一個文件,我想在其中找到關鍵字並輸入兩行以下的文字。
例如,假設我的文件包含以下單字
the
cow
goes
moo
我希望能夠找到“cow”一詞,並將文字“yay”輸入文件中“cow”一詞下方 2 行。
the
cow
goes
moo
yay
我相信這可以完成,sed
但無法使其發揮作用。
任何幫助是極大的讚賞。
答案1
$ cat ip.txt
the
cow
goes
moo
$ sed '/cow/{N;N; s/$/\nyay/}' ip.txt
the
cow
goes
moo
yay
N;N;
取得接下來的兩行s/$/\nyay/
新增另一行
答案2
和awk
:
awk '/cow/ {print; getline; print; getline; print; print "yay"; next}; 1'
/cow/
匹配cow
記錄,然後{print; getline; print; getline; print; print "yay"; next}
列印該行,getline
取得下一行,也列印,下一行相同,然後yay
列印,然後轉到下一行(next
)1
(true) 將列印其餘行作為預設操作
警告:
- 如果要搜尋的模式和 EOF 之間的行數少於兩行,則會重複從模式開始的最後一行,以在兩者之間形成兩行
例子:
% cat file.txt
the
cow
goes
moo
% awk '/cow/ {print; getline; print; getline; print; print "yay"; next}; 1' file.txt
the
cow
goes
moo
yay
答案3
其他sed
sed '/cow/! b;n;n;a\yay' file.txt
其他awk
awk '{print;this--};/cow/{this=2}! this{print "yay"}' file.txt
答案4
和ed
ed file << EOF
/cow/+2a
yay
.
,p
q
EOF
列印修改後的輸出;或者
ed file << EOF
/cow/+2a
yay
.
wq
EOF
或(作為bash
單行)
printf '%b\n' '/cow/+2a' 'yay\n.' 'wq' | ed file
將變更寫入到位。