使用 sed 替换双引号字符之间的斜杠 [英] Replace slashes between double quote characters using sed

查看:62
本文介绍了使用 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 else
  • s/\//%20/g replace /'s by %20's
  • H append the amended replacements to the original line
  • g overwrite the pattern space with the HS.
  • :a;s/\n"[^"]*"\(.*\n\)\n\("[^"]*"\)/\2\1/;ta one at a time replace the old with new
  • s/\n// delete the \n introduced when the H was used

尝试在上述解决方案中插入 l0 以查看模式空间中的内容.

Try inserting l0 in the above solution to see what is in the pattern space.

这篇关于使用 sed 替换双引号字符之间的斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆