sed替换正则表达式正确的语法

时间:2020-09-17 06:26:16

标签: sed

<div data-name="abc" data-location="abcd"><div>Something</div></div>

sed 's/data-name="*"/data-name="helloworld"/g' 

我正在尝试将data-name="abc" abc替换为helloworld

但是,我的结果返回了

data-name="helloworld"helloworld"abc"

我希望成为data-name="helloworld"

2 个答案:

答案 0 :(得分:1)

*匹配零个或多个前置字符。因此"*匹配零个或多个"字符。因此data-name="*"匹配了data-name=""*匹配了零个字符)并将其替换。

您似乎想实际匹配"中的文本。因此,将所有内容匹配到"

sed 's/data-name="[^"]*"/data-name="helloworld"/g'

请注意,you can't parse html with regex最好使用XML感知工具来编辑html。用正则表达式填字游戏学习正则表达式很有趣。

答案 1 :(得分:0)

尽管html文件应该由html适当的解析器解析,因为OP已经与工具sed一起使用,因此请使用awk添加此解决方案。

awk -v str="helloworld" '
match($0,/"[^"]*/){
  print substr($0,1,RSTART) str substr($0,RSTART+RLENGTH)
  next
}
1
' Input_file

使用sed

sed 's/\(^[^"]*\)\("[^"]*"\)\(.*\)/\1"helloworld"\3/' Input_file

如果要查找具有data-name字符串的行,则可以在上述解决方案中将match($0,/"[^"]*/){行更改为/data-name/ && match($0,/"[^"]*/){,将s/更改为/data-name/s