sed搜索替换模式

时间:2013-10-25 10:30:10

标签: regex bash shell sed

我的文件有以下文字(及以上)。

import (
    "http"
    "web"
)

我想将所有"web"替换为"pkg/web"(在所有文件中)。所以结果需要

 import (
        "http"
        "pkg/web"
    )

我尝试sed喜欢

find . -type f -print0 | xargs -0 sed -i '/"web"/c\"pkg/web"'

给出了错误。

sed: 1: "test" invalid command code .

正确的方法是什么?

感谢。

2 个答案:

答案 0 :(得分:1)

问题是您使用/作为正则表达式分隔符,但在替换字符串中也使用/

好消息是sed允许使用不同的正则表达式分隔符。

这个带有不同正则表达式分隔符的sed应该可以工作:

sed -i.bak 's~^\( *\)"web" *$~\1"pkg/web"~g'

更新:要在搜索字符串的LHS上保留空白:

find . -type f -print0 | xargs -0  sed -i '' 's~^\([[:space:]]*\)"web"[[:space:]]*$~\1"pkg/web"~g'

答案 1 :(得分:0)

  找到。 -type f -print0 | xargs -0 sed -i -e的@“web”@“pkg / web”@g'

这对我来说很好。