【问题标题】:How to replace multiple lines between two patterns with content of a file using sed?如何使用 sed 用文件内容替换两个模式之间的多行?
【发布时间】:2020-06-18 03:50:13
【问题描述】:

假设我的文件中有以下内容
文件1.txt:

some text ...
...    
begin  
    if somthing is true  
       some text here  
       ...  
    fi 
end  
some text

我想用内容替换开始结束之间的文本,包括开始结束 另一个文件
文件2.txt:

while read line:  
do  
   some code
done

替换后的file1.txt应该是这样的
文件1.txt:

some text ...
...    
while read line:  
do  
   some code
done
some text

【问题讨论】:

  • 到目前为止你做了什么?
  • 我无法理解你的问题...
  • 您有一些代码要添加到您的问题中吗?

标签: sed substitution paragraph


【解决方案1】:

你可以试试这个 sed

sed -e '/begin/,/end/!b' -e '/end/!d;r file2.txt' -e 'd' file1.txt

如果未指定选项 -n,则 Sed 打印文件的每一行。
在打印之前,sed 执行所有 -e 选项给出的脚本。
脚本中的命令 b 告诉 sed 在此时结束脚本。
所以第一个 -e 命令告诉 sed 结束脚本并打印所有不在 begin 和 end 中的行。
第二个 -e 命令告诉 sed 在找到带有 end 的行时打印文件 file2.txt。
第三个 -e 命令告诉 sed 从头到尾删除(不打印)行。

【讨论】:

  • 哇,这很严重sed。我阅读了文档,但我仍然没有真正理解。你能把它分解一下吗?
  • @brandones 我为您编辑帖子并尝试解释其工作原理。
【解决方案2】:

关注awk 可能对您有所帮助。

awk '/begin/{print;system("cat FIlE2.txt");next} 1' FIlE1.txt

输出如下。

some text ...
...
begin
while read line:
do
   some code
done
    if somthing is true
       some text here
       ...
    fi
end

【讨论】:

    猜你喜欢
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多