使用 sed 替换双引号字符之间的斜杠 [英] Replace slashes between double quote characters using sed
本文介绍了使用 sed 替换双引号字符之间的斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 HTML 文件中,我试图用 %20
替换出现在一对双引号 "
之间的斜线 /
.例如,而不是有这一行:
In an HTML file, I'm trying to replace the slashes /
that appear between a pair of double quotes "
with %20
.
For example instead of having this line:
<a href="i/love/unix">i/am/happy!</a>
我想得到:
<a href="i%20love%20unix">i/am/happy!</a>
我正在尝试像这样使用 sed
命令:
I'm trying to use the sed
command something like this:
sed -e 's/\(^.*href=\"\).*\(\".*\)/\1@@@\2/g'
但是我尝试使用另一个 sed
命令代替 '@@@',将 /
替换为 %20
:
But instead of '@@@', I'm trying to use another sed
command to replace /
with %20
:
's/\//%20/g'
是否可以将这两个 sed
命令组合在一起?
Is it possible to combine these two sed
commands together?
推荐答案
这可能对你有用(GNU sed):
This might work for you (GNU sed):
echo '<a href="i/love/unix">i/am/happy!</a>' |
sed 's/"[^"]*"/\n&/g;h;s/[^"\n]*\(\n"[^"]*"\)[^"\n]*/\1/g;s/\//%20/g;H;g;:a;s/\n"[^"]*"\(.*\n\)\n\("[^"]*"\)/\2\1/;ta;s/\n//'
<a href="i%20love%20unix">i/am/happy!</a>
说明:
s/"[^"]*"/\n&/g
在每个预期字符串前全局插入一个\n
,即"..."
h
在保留空间 (HS) 中进行复制s/[^"\n]*\(\n"[^"]*"\)[^"\n]*/\1/g
删除所有其他内容s/\//%20/g
将/
替换为%20
的H
将修改后的替换附加到原始行g
用 HS 覆盖模式空间.:a;s/\n"[^"]*"\(.*\n\)\n\("[^"]*"\)/\2\1/;ta
一次一个,用新的替换旧的s/\n//
删除使用H
时引入的\n
s/"[^"]*"/\n&/g
globally insert a\n
before each intended string i.e."..."
h
make a copy in the hold space (HS)s/[^"\n]*\(\n"[^"]*"\)[^"\n]*/\1/g
remove everything elses/\//%20/g
replace/
's by%20
'sH
append the amended replacements to the original lineg
overwrite the pattern space with the HS.:a;s/\n"[^"]*"\(.*\n\)\n\("[^"]*"\)/\2\1/;ta
one at a time replace the old with news/\n//
delete the\n
introduced when theH
was used
尝试在上述解决方案中插入 l0
以查看模式空间中的内容.
Try inserting l0
in the above solution to see what is in the pattern space.
这篇关于使用 sed 替换双引号字符之间的斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文