【问题标题】:Sed replace entire line with replacementsed 用替换替换整行
【发布时间】:2012-03-23 04:29:35
【问题描述】:

我不久前在超级用户上发布了this question,但我还没有得到我喜欢的答案。在这里,稍作修改。

我希望有一种方法可以让 sed 用替换替换整行(而不仅仅是匹配),这样我就可以做这样的事情:

sed -e "/$some_complex_regex_with_a_backref/\1/"

并让它只打印反向引用。

this question 看来,这样做的方法是使用正则表达式来匹配整行,或者使用其他工具(如 perl)。简单地将 regex 更改为 .*regex.* 并不总是有效(如该问题所述)。例如:

$ echo $regex
\([:alpha:]*\)day

$ echo "$phrase"
it is Saturday tomorrow
Warm outside...

$ echo "$phrase" | sed "s/$regex/\1/"
it is Satur tomorrow
Warm outside...

$ echo "$phrase" | sed "s/.*$regex.*/\1/"

Warm outside...

$ # what I'd like to have happen
$ echo "$phrase" | [[[some command or string of commands]]]
Satur
Warm outside...

我正在寻找最简洁的方法来替换整行(不仅仅是匹配部分),假设如下:

  • 正则表达式位于变量中,因此不能根据具体情况进行更改。
  • 我想在不使用 perl 或其他更强大的语言(sed、awk、grep 等都可以)的情况下执行此操作
  • 该解决方案无法删除与原始正则表达式不匹配的行(抱歉grep -o 没有删除它)。

我想到的是以下(但它很丑,所以我想知道是否有更好的东西):

$ sentinel=XXX
$ echo "$phrase" | sed "s/$regex/$sentinel\1$sentinel/" |
> sed "s/^.*$sentinel\(.*\)$sentinel.*$/\1/"

【问题讨论】:

    标签: regex sed awk grep


    【解决方案1】:

    这可能对你有用:

    sed '/'"$regex"'/!b;s//\n\1\n/;s/.*\n\(.*\)\n.*/\1/' file
    

    【讨论】:

    • 你在哪里看到\n阅读sentinel。由于 sed 使用\n 作为行分隔符,\n 不能出现在模式空间中,除非它是由用户插入的。因此它是理想的哨兵
    猜你喜欢
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 2010-11-16
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多