【问题标题】:Need help in converting perl RegExp query to sed one在将 perl RegExp 查询转换为 sed 时需要帮助
【发布时间】:2014-05-30 16:42:34
【问题描述】:

我已经编写了用于解析输入文本/文件的 perl 脚本,如下所示:

[root@agent tmp]# head ./test_regqexp_keynote.txt
alert@keynote.com       (Top20) Carnation GB/fd (Crit)  9:57    11 KB
alert@keynote.com       (Shell Brand EUR) HealthScience NL/fd (Crit)    9:36
11 KB
alert@keynote.com       (Shell Corp AMS) Nestle JP/fd (Crit)    9:16    11 KB
alert@keynote.com       (Top20) NestleHealth DE/fd (Crit)       9:01    11 KB
alert@keynote.com       (Shell Corp AMS) Nestle NZ/fd (Crit)    8:17    12 KB
alert@keynote.com       (Shell Brand EUR) HealthScience CH/fd (Crit)    8:11
11 KB
alert@keynote.com       (Shell Corp AMS) Nestle CL/fd (Crit)    8:11    11 KB
alert@keynote.com       (Shell Corp AMS) Nestle VE/fd (Crit)    8:11    11 KB

并在输出中获取如下文本:

HealthScience FI/fd
DolceGusto NZ/fd
Waters WW/fd
Nestle UA/fd
Nestle SK/fd
Nestle SI/fd

perl -ne 'if ($_=~ m/([a-zA-Z]* [A-Z]{2,3}\/fd)/) {print "$1\n";}'

所以只是“XXXX XX/fd”部分的摘录。

但我需要使用 SED 工具来完成。

这让我发疯了。似乎 SED 以完全不同的方式工作或具有非常不同的 RegEx 规则。

请帮我将此 RegExp 查询转换为 SED RegExp 查询。或者解释一下 Sed RegExp 与 Perl 或 Egrep RegExp 的主要区别。

【问题讨论】:

  • 谢谢大家!很棒且有用的答案。

标签: regex perl bash sed grep


【解决方案1】:

这是一种方法:

sed -n 's!.* \([a-zA-Z]* [A-Z]\{2,3\}/fd\).*!\1!p' input

也许这也可以:

sed -n 's!.* \([^ ]* [^ ]*/fd\).*!\1!p' input

【讨论】:

    【解决方案2】:
    sed -n 's#.* \([a-zA-Z]* [A-Z]\{2,3\}/fd\).*#\1#p' test_regqexp_keynote.txt
    

    或者:

    egrep -o '[a-zA-Z]* [A-Z]{2,3}/fd' test_regqexp_keynote.txt
    

    【讨论】:

      【解决方案3】:

      不用复杂的正则表达式,你可以试试这个awk

      awk -F"[)] | [(]" 'NF>3{print $3}' file
      Carnation GB/fd
      HealthScience NL/fd
      Nestle JP/fd
      NestleHealth DE/fd
      Nestle NZ/fd
      HealthScience CH/fd
      Nestle CL/fd
      Nestle VE/fd
      

      【讨论】:

      • 你能解释一下这个字段分隔符是如何工作/由 AWK 解析的吗? -F"[)] | [(]" 我认为我们应该只在此处指向 1 个符号,例如 : 或 ( 或任何其他符号。
      • @user2273663 您可以在FS 字段分隔符中使用任何正则表达式,在gnu awk 上您可以在RS 中执行相同操作。 | 是一个或。所以在这里你得到) 或`(`作为分隔符。由于括号是正则表达式中的特殊命令,并且转义不起作用\(,我们使用括号[(]。eks:[a-c]|12ab c12 作为分隔符。
      • @user2273663 如果你喜欢我的回答,可以给+1
      • @user2273663,我希望我能给你 +1。我试过了。收到消息说我还没有足够的声誉。 (((
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-04
      相关资源
      最近更新 更多