【问题标题】:How to replace 3rd word in a line using sed如何使用 sed 替换一行中的第三个单词
【发布时间】:2011-03-17 13:25:05
【问题描述】:

这是我学习 sed 过程中的第 3 篇文章。我有一个假设的要求。我希望能够将每行中的第三个单词替换为“was”,其中单词由空格分隔。

bash$ cat words
hi this is me here
hi this   is me again
hi   this   is me yet again
 hi  this   is     me

期望的输出:

hi this was me here
hi this   was me again
hi   this   was me yet again
 hi  this   was     me

请大家帮忙看看如何用 sed 来做这件事。我尝试了一些执行指令,但没有奏效。 谢谢,

贾格拉蒂

我找到了!我找到了!

好的,我终于得到了正确的指示。这有效:

sed -e 's/[^ ]*[^ ]/was/3' words

【问题讨论】:

    标签: linux shell sed awk replace


    【解决方案1】:

    如果您不关心格式,这是一种更简单的方法

    $ awk '{$3="was"}1' file
    hi this was me here
    hi this was me again
    hi this was me yet again
    hi this was me
    

    【讨论】:

    • +1,awk不错,刚开始读awk编程语言。
    • }' 之间的 1 是什么意思?
    【解决方案2】:

    我总是这样做:使用 groups 匹配第一个和第二个单词,然后使用 backreference 将它们替换为自己。

    sed 's/^\([^ ]*\) \([^ ]*\) is/\1 \2 was/'
    

    【讨论】:

    • 这会因为空格数不均匀而失败。
    • 没错,当我尝试它时,它能够在第一行替换,但不能在后面的。
    • sed 's/^ *([^ ]*)\ \+([^ ]*) \+is/\1 \2 was/' 文件 > 结果
    • 我知道,我正在演示该方法,我相信您可以自己调整正则表达式。
    【解决方案3】:

    这会查看单词边界而不仅仅是空格,因此在有标点符号时也可以使用。它需要 GNU sed:

    $ cat words
    hi this is me here
    hi this   is me again
    hi   this   is me yet again
     hi  this   is     me
     hi   this   "is,  me
    $ sed 's/\w\+\(\W\)/was\1/3' words
    hi this was me here
    hi this   was me again
    hi   this   was me yet again
     hi  this   was     me
     hi   this   "was,  me
    

    【讨论】:

      【解决方案4】:

      在任何类型的 sed 中:

      sed 's/^\([[:blank:]]*[^[:blank:]]\{1,\}[[:blank:]]\{1,\}[^[:blank:]]\{1,\}[[:blank:]]\{1,\}\)[^[:blank:]]\{1,\}\(.*\)$/\1was\2/' words
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-23
        • 1970-01-01
        • 2011-03-20
        • 2015-04-03
        • 2021-10-08
        • 2020-09-01
        • 1970-01-01
        • 2018-10-30
        相关资源
        最近更新 更多