在文件中搜索关键字并替换它旁边的行

时间:2013-04-26 04:19:07

标签: shell unix sed

我有一个需要通过shell脚本修改的文件。

需要执行以下操作: 1.在文件中搜索关键字。 2.用我提供的行文本替换此关键字的下一行。

例如,我的文件包含以下文字:

(一些文字) (一些文字) (搜寻文字) (TEXT_TO_REPLACE) (一些文字) (一些文字) (一些文字)

我需要搜索文件并重写文件替换该行,保持其余内容不变。

如何做到这一点?

此致

3 个答案:

答案 0 :(得分:2)

awk ' zap==1 {print "my new line goes here"; zap=0; next}
      /my pattern/ {zap=1; print $0; next}
      {print $0} '  infile > newfile

假设我得到了你想要的东西......

   var="this is the line of text to insert" 
   awk -v lin="$var"  ' zap==1 {print lin ; zap=0; next}
          /my pattern/ {zap=1; print $0; next}
          {print $0} '  infile > newfile

awk内部变量lin,已定义:-v lin="$var"名为linlin来自外部bash变量var

答案 1 :(得分:0)

 sed -i '/pattern/r/dev/stdin' file

脚本将等待我们进入换行符并按交互式按Ctrl + d

答案 2 :(得分:0)

   cat file

first
second
third
fourth
fiveth

set var = "inserted"
sed '/second/a\'$var file

first
second
inserted
third
fourth
fiveth
相关问题