【问题标题】:Find specific text in file and wrap in with other text在文件中查找特定文本并用其他文本换行
【发布时间】:2012-02-26 20:15:41
【问题描述】:

我正在寻找从 Linux 命令行中查找文件中特定文本并在其周围环绕其他文本的最佳方法。

例如,该文件可能包含以下内容:

This
is
a
test.
anchor-start
text to wrap will is in here
anchor-end

所以在上面的例子中,我想在anchor-start 和anchor-end 之间找到文本,然后将文本换行,这样我就得到了:

This
is
a
test.
anchor-start
wrapping-start
text to wrap will is in here
wrapping-end
anchor-end

我还应该注意,我正在寻找一种解决方案,如果anchor-start 后面紧跟wrapping-start(即包装已经发生),那么它不应该被复制。

【问题讨论】:

  • 查看 sed 并将 anchor-start 替换为 anchor-start\nwrapping-start 和 anchor-end 替换为 wrapping-end\nanchor-end
  • 要排除双重包装,您可以使用否定环视e.g., in Perl。

标签: regex linux sed awk


【解决方案1】:

这可能对你有用:

sed '/anchor-start/,/anchor-end/{/anchor-start/{h;d};H;/anchor-end/{x;/wrapping-start/b;s/\n.*\n/\nwrapping-start&wrapping-end\n/p};d}' file
This
is
a
test.
anchor-start
wrapping-start
text to wrap will is in here
wrapping-end
anchor-end

【讨论】:

    【解决方案2】:
    pearl.319> cat temp.pl
    This 
    is a 
    test. 
    anchor-start
    text to wrap will 
    is in here 
    anchor-end
    pearl.320> perl -p -e 's/anchor-start/anchor-start\nwrap-start/g;s/anchor-end/wrap-end\nanchor-end/g' temp.pl
    This 
    is a 
    test. 
    anchor-start
    wrap-start
    text to wrap will 
    is in here 
    wrap-end
    anchor-end
    

    【讨论】:

      猜你喜欢
      • 2012-12-10
      • 2012-10-17
      • 2019-01-30
      • 1970-01-01
      • 1970-01-01
      • 2021-01-23
      • 2016-06-29
      • 2013-05-03
      • 1970-01-01
      相关资源
      最近更新 更多