【问题标题】:SED - Regex failsSED - 正则表达式失败
【发布时间】:2019-11-09 15:43:56
【问题描述】:

给定以下文件:

输入文件:

if_line1
if_line2

template_file_1:

temp_file_line1
temp_file_line2

##regex_match## <= must be replaced by input_file

temp_file_line3

template_file_2:

temp_file_line1
temp_file_line2

{my_file.global} <= must be replaced by input_file

temp_file_line3

输出文件:

temp_file_line1
temp_file_line2

if_line1
if_line2

temp_file_line3

对于 template_file_1,以下 sed 命令有效:

sed -n -e '/##regex_match##/{r input_file' -e 'b' -e '}; p' template_file_1 > output_file

但是,对于 template_file_2,模拟 sed 命令失败:

sed -r -n -e '/(?<={).+\.global(?=})/{r input_file' -e 'b' -e '}; p' template_file_2 > output_file

sed 抱怨正则表达式无效

给定的正则表达式至少 PCRE 有效,例如 grep -oP '(?&lt;={).+\.global(?=})' template_file_2 有效。知道如何处理吗?

【问题讨论】:

  • sed 不支持 PCRE,仅支持 POSIX BRE/ERE 正则表达式。
  • 您是否知道如何在没有环视的情况下实现这一点?检测 {my_file.global} 并提取 my_file.global,不带大括号?
  • Perl 支持 Perl 正则表达式,带有环视和诸如此类的东西。为什么需要 sed?
  • 好吧,它似乎可以与/\{.+\.global}/、sed -r -n -e '/\{.+\.global}/{r input_file' -e 'b' -e '}; p' template_file_2 &gt; output_file一起使用
  • @glennjackman 实际上,OP 使用的是-r,它与-E 相同。我知道-E 更便携,但它适用于 OP,也适用于我。

标签: regex bash sed pcre


【解决方案1】:

确切地知道 PCRE 打算做什么,但猜测一下,这将在每个 UNIX 机器上的任何 shell 中使用任何 awk 工作:

$ awk 'NR==FNR{new=new s $0; s=ORS; next} /##regex_match##/{$0=new} 1' input_file template_file_1
temp_file_line1
temp_file_line2

if_line1
if_line2

temp_file_line3

$ awk 'NR==FNR{new=new s $0; s=ORS; next} /\{[^.{}]+\.global}/{$0=new} 1' input_file template_file_2
temp_file_line1
temp_file_line2

if_line1
if_line2

temp_file_line3

【讨论】:

  • 一如既往的出色解决方案先生。
【解决方案2】:

perl 单行代码:

perl -pe 'do {local $/; open $f, "<input_file"; $_ = <$f>; close $f} if /\{.+?\.global\}/' template_file_2

或者也许是这个,而不是“纯”perl

perl -ne 'if (/\{.+?\.global\}/) {system("cat","input_file")} else {print}' template_file_2

使用 CPAN 模块可以使这变得非常整洁:

perl -MPath::Tiny -pe '$_ = path("input_file")->slurp if /\{.+?\.global\}/' template_file_2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多