[英]Sed substitute pattern within a line
How can I substitute characters only within a specific pattern, preferably in sed but awk or otherwise if there's an easier option? 如果有更简单的选择,我该如何仅在特定模式(最好是sed但awk或其他)中替换字符? I would like to replace spaces in my html h3 ids with hyphens (-), but I don't want it to hyphen the entire line.
我想用连字符(-)替换html h3 id中的空格,但是我不希望它用连字符代替整行。
Eg, in my foo.html: 例如,在我的foo.html中:
<p>This is a paragraph which likes its spaces.</p>
<h3 id="No spaces in this id please">Keep spaces in this title</h3>
<p>Here's another paragraph with spaces.</p>
<h3 id="Another id that should be spaceless">Spaces please!</h3>
<p>Yes I would like extra noodles in my soup.</p>
What I want are h3s like this: 我想要的是这样的h3:
<h3 id="Another-id-that-should-be-spaceless">Spaces please!</h3>
I've tried 我试过了
sed -e "/^<h3 id=\"/,/\">/s/ /-/g;" <foo.html >bar.html
But this greedily adds hyphens to lines (2nd p) and parts (h3 content) which shouldn't have hyphens! 但是,这会贪婪地在不应该使用连字符的行(第二行)和部分(h3内容)中添加连字符! Bar.html:
一个bar.html:
<p>This is a paragraph which likes its spaces.</p>
<h3-id="No-spaces-in-this-id-please">Keep-spaces-in-this-title</h3>
<p>Here's-another-paragraph-with-spaces.</p>
<h3-id="Another-id-that-should-be-spaceless">Spaces-please!</h3>
<p>Yes I would like extra noodles in my soup.</p>
Note I'm using GNU sed. 注意我正在使用GNU sed。 Thanks!
谢谢!
This sed replace one space at a time in the id
value of h3
tags. 此sed一次替换
h3
标签的id
值中的一个空格。 When substitution succeeds, the t
command loops to :a
label to search for remaining spaces to replace: 替换成功后,
t
命令循环到:a
标签以搜索要替换的剩余空间:
sed -e ':a;s/\(<h3[^>]*id="[^"> ]*\) \(.*\)/\1-\2/;ta;' < foo.html > bar.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.