只有在特定的字符串替换字符 [英] Replace character only in certain string

查看:106
本文介绍了只有在特定的字符串替换字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要更换每一个_, - ,在HTML文件中,但只有在标签,只有在name属性。

所以每次这样的:

 < A NAME =menu_portlet_test>或LT; A NAME =whatever_is_here>

应该成为这样的:

 <名称=菜单中的portlet测试>和< A NAME =无论-是,这里>

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


解决方案

  sed的':一个
S / \\(小于[^>] * NAME =[^] * \\)_ \\([^] *\\)/ \\ 1 \\ 2 /克; TA'YourFile

应该做你最工作。并不完美,由于顶部HTML可能性,但应该是99.9%确定

的解释

取值//摹


  • 搜索模式(< 后跟任何非> ([^>]的 ),其次是 NAME =后跟(任何非 [^] ))为第1组],然后按 [所以首先 名后报价之间=],然后(任何非 [^] * ),其次是`)作为第2组]

  • 将遵循组1的含量进行更换 - 其次是2组
  • 内容
  • 先按g 这样做对就行了任何occurence。这种变化1 _每名=,但是,任何名称=行。 < ... NAME =bla_bla_bla> ...< ... NAME =other_bla_bla> ... NAME =BLA-bla_bla> ... &LT变化; ...< ... NAME =其他-bla_bla> ...

TA


  • 如果变化发生在previous 取值// ,重做与修改的内容相同的动作(其实这是一个如果/转到标记:一个

I need to replace every "_" with "-" in html file but only in tag and only in "name" attribute.

So every this:

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

should become this:

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

Can't figure out how to force something like sed/awk to do it. Help!

解决方案

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

Should do most of you job. Not perfect due top html possibilities but should be 99,9% ok

explaination

s//g

  • Search the pattern ( < followed by any non > ([^>]) followed by name="followed by (any non"([^"]) ) [ as group 1] followed by[so firstbetween quote after name=] followed by ( any non"([^"]*) followed by"`) [ as group 2 ]
  • Replace it by content of group 1 followed by - followed by content of group 2
  • g do it for any occurence on the line. This change 1 _ per name="" but on any name= of the line. <... name="bla_bla_bla"> ... <... name="other_bla_bla"> ... change to <... name="bla-bla_bla"> ... <... name="other-bla_bla"> ...

ta

  • if a change occur in previous s//, redo the same action with modified content( in fact it is a if/goto to label :a)

这篇关于只有在特定的字符串替换字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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