sed替换正则表达式匹配的特定子str

时间:2014-07-02 13:09:07

标签: sed

我想替换' /'与' $'在子字符串中。如下所示:

{"url":"www.xxx.com/a/b/x/", "title":"hello world", "type":"c/python/perl", "content":"Just use sed"}

我想更改子字符串' c / python / perl '到' c $ python $ perl ',是什么优雅的sed解决方案

我可以使用' \ 1'返回引用匹配c / python / perl,然后使用' \ 1'?

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以使用以下sed命令,而不需要使用捕获组。

sed 's~c/python/perl~c$python$perl~' file

示例:

$ echo '{"url":"www.xxx.com/a/b/x/", "title":"hello world", "type":"c/python/perl", "content":"Just use sed"}' | sed 's~c/python/perl~c$python$perl~'
{"url":"www.xxx.com/a/b/x/", "title":"hello world", "type":"c$python$perl", "content":"Just use sed"}

<强>更新

$ echo '{"url":"www.xxx.com/a/b/x/", "title":"hello world", "type":"c/python/perl", "content":"Just use sed"}' | awk -F, -v OFS="," '{gsub(/\//,"$",$3)}1'
{"url":"www.xxx.com/a/b/x/", "title":"hello world", "type":"c$python$perl", "content":"Just use sed"}

答案 1 :(得分:0)

可以使用sed的反向引用作为bash函数的参数。但是,他们在这里说:using command substitution inside a sed script, with argumentssed不会执行任何命令。

仍然可以使用正则表达式的perl修饰符来处理e

echo '{"url":"www.xxx.com/a/b/x/", "title":"hello world", "type":"c/python/perl", "content":"Just use sed"}' \
    | perl -pe 's/(?<="type":")([^"]*)/`echo -n $1 | tr "\/" "\$"`/e'