如何在文件中找到單字並在其下方插入兩行文字?

如何在文件中找到單字並在其下方插入兩行文字?

我有一個文件,我想在其中找到關鍵字並輸入兩行以下的文字。

例如,假設我的文件包含以下單字

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

將變更寫入到位。

相關內容