sed替换与regex匹配的特定子str

sed替换与regex匹配的特定子str,sed,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解决方案是什么 我可以使用反向引用将c/python/perl与'\1'匹配,然后对'\1'执行某些操作吗 谢谢 您可以使用下面的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解决方案是什么

我可以使用反向引用将c/python/perl与'\1'匹配,然后对'\1'执行某些操作吗


谢谢

您可以使用下面的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"}
更新:

$ 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"}

可以使用
sed
的反向引用作为bash函数的参数。然而,他们在这里说:,
sed
不会执行任何命令

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

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'
echo'{“url”:“www.xxx.com/a/b/x/”,“title”:“hello world”,“type”:“c/python/perl”,“content”:“Just use sed”}\

|perl-pe的/(?首先谢谢。但是“type”字段可能是其他字符串,如“java/c++”。我需要一个通用的解决方案。字段是否相同?例如,首先是URL,然后是标题,然后像那样键入。e,我知道awk解决方案。我只想知道我可以在sed中使用反向引用\1做些什么。但您不确定该值是否包含两个或一个正斜杠。我是正确的吗?@augusto您的意思是这个
sed-r的/^(.*\\\“:\”)(\w+)\/(\w+)\/(\w+)/(\”*)$/\1\2$\3$\4\5/g'
是否有如下解决方案:sed's/(reg)/;s/\/$/g'我不明白你的意思。请进一步解释。我的意思是:cat\1 | sed's/\/$/g'像这样你最好的意思是:
echo\1 | tr'/''$'
。根据链接页面,这在
sed
中是不可能的,因为sed不会执行外部
tr
(或者
sed
)这就是为什么我使用perl并从那里调用external
tr
command,以显示perl对
sed
的调用非常类似是可能的。实际上,您可以键入
perl-pe
,而不是
sed
,并且基本上具有相同的功能,具有更好的正则表达式和更多的可能性,包括您的需求。