【问题标题】:Replacing first occurance of a match with sed用 sed 替换第一次出现的匹配项
【发布时间】:2012-02-27 02:59:38
【问题描述】:

我正在使用 sed 进行查找和替换,将 BASH 变量 $a(在新行的开头)替换为 BASH 变量 $b

sed -i "s#^$a#$b#" ./file.txt

这将替换 ^$a 的所有匹配项。如何仅替换整个文件中第一次出现的 ^a

【问题讨论】:

  • 我使用的是 GNU sed 4.2.1 版。

标签: bash sed


【解决方案1】:

一种使用sed的方式:

sed "s/^$var1/$var2/ ; ta ; b ; :a ; N ; ba" infile

解释:

s/^$var1/$var2/             # Do substitution.
ta                          # If substitution succeed, go to label `:a`
b                           # Substitution failed. I still haven't found first line to 
                            # change, so read next line and try again.
:a                          # Label 'a'
N                           # At this position, the substitution has been made, so begin loop
                            # where I will read every line and print until end of file.
ba                          # Go to label 'a' and repeat the loop until end of file.

与 Jaypal 提供的相同示例的测试:

infile的内容:

ab aa
ab ff
baba aa
ab fff

运行命令:

sed "s/^$var1/$var2/ ; ta ; b ; :a ; N ; ba" infile

结果:

bb aa
ab ff
baba aa
ab fff

【讨论】:

    【解决方案2】:

    这应该可行:

    sed -i "0,/^\$a/s//\$b/" ./file.txt
    

    您可以在http://www.grymoire.com/Unix/Sed.html#toc-uh-29阅读更多相关信息

    【讨论】:

    • 当我尝试这个时,我得到“sed: -e expression #1, char 3: unexpected `,'”。
    • 是的,我使用“$”而不是“/”,因为有些要替换的项目包含“/”,但不包含任何“#”。
    • 我认为你不应该在 sed 脚本中的双引号之间转义 $ 以在其中使用 bash 变量。
    • 如果您的项目包含/,您可以使用\/ 对其进行转义。
    • @Village:您需要转义第一个#。试试这个:sed -i "0,\#^$a#s##$b#" ./file.txt。我删除了美元符号之前的转义符,因此将替换变量值。请注意,0,addr2 的地址形式特定于 GNU sed(您正在使用)。
    【解决方案3】:

    这可能对你有用:

     sed -i 'x;/^./{x;b};x;/^'"$a"'/{s//'"$b"'/;h}' file
    

    或者:

     sed -i ':a;$!{N;ba};s/^'"$a/$b"'/m' file
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-30
      • 1970-01-01
      相关资源
      最近更新 更多