2014-09-10 74 views
0

我需要在html文件中将每个“_”替换为“ - ”,但只能在标记中并且仅在“名称”属性中替换。只替换特定字符串中的字符

所以每到这一点:

<a name="menu_portlet_test"> or <a name="whatever_is_here"> 

应该成为这样的:

<a name="menu-portlet-test"> and <a name="whatever-is-here"> 

无法弄清楚如何迫使像SED/AWK做到这一点。帮帮我!

+3

使用sed/awk解析HTML,避免,避免,避免。 – anubhava 2014-09-10 10:02:49

+0

看看[这个答案](https://stackoverflow.com/a/1732454/1820501)。 – 2014-09-10 10:08:24

+0

@AvinashRaj:this'

'也匹配 – 2014-09-10 10:53:45

回答

2
sed ':a 
s/\(<[^>]* name="[^"]*\)_\([^"]*"\)/\1-\2/g;ta' YourFile 

应该做的最让你工作。不完美的,由于上面的html可能性,但应该是99.9%确定

交代

s//g

  • 搜索模式(<后跟任何非>([^>] ) followed by名=“followed by (any non( [^“])) [ as group 1] followed by[so firstbetween quote after name=] followed by (any non( [^ “] * ) followed by”`)[按组2]
  • 通过随后-组1的内容,随后组的内容2
  • g做它为线路上的任何occurence更换。此更改1 _每名=“”,但在任何名称=行上。 <... name="bla_bla_bla"> ... <... name="other_bla_bla"> ...变化<... name="bla-bla_bla"> ... <... name="other-bla_bla"> ...

ta

  • 如果改变发生在以前的s//,重做与修改的内容相同的动作(实际上,它是一个如果/ GOTO到标签:a
+0

似乎在伎俩,谢谢,现在我必须弄清楚它是如何工作的:)。 编辑:啊!一个循环,辉煌! – user1606576 2014-09-11 11:02:37

+0

增加了一些评论来解释 – NeronLeVelu 2014-09-12 09:17:35

1

使用合适的HTML处理工具,例如xsh,围绕Perl's XML::LibXML的包装。下面的命令可以被保存在一个脚本,或者从它的互动环境中输入:

open :F html file.html ; 
for //@name set . xsh:subst(., '_', '-', 'g') ; 
save :b ; 
+0

看起来很有意思,您从交互式shell中运行的这些命令也是如此?也许答案中的一些更多细节会很有用。 – 2014-09-10 10:39:40

+1

@TomFenech:更新,谢谢。 – choroba 2014-09-10 10:41:06