简体   繁体   English

赛前插入sed

[英]Sed insert before first match

I want to insert a string in html before the first "<p" in the file, however I am having some difficulty. 我想在文件的第一个“ <p”之前在html中插入字符串,但是遇到了一些困难。

thestring="<p>this is some sentence</p>"
sed -i "/<p/i${thestring}" somefile.html

"somefile.html" however contains multiple lines containing "<p" and the above inserts the string multiple times. 但是,“ somefile.html”包含多行包含“ <p”的行,并且上面多次插入了字符串。

I have tried doing this: 我尝试这样做:

sed -i "0,/<p/i${thestring}" somefile.html

or 要么

sed -i "0,/<p/s//i${thestring}" somefile.html

but I'm getting no where. 但是我什么也没有。

What am I doing wrong? 我究竟做错了什么?

two things you may consider : 您可能会考虑两件事:

1) use s/.../.../ instead of i 1)使用s/.../.../代替i

2) special chars in your thestring which would conflict with sed's s separator. 2)在你的特殊字符thestring这将使用sed的冲突s分离。 In your example the slash in /p> 在您的示例中, /p>的斜杠

this should work for your needs: 这应该可以满足您的需求:

 sed  -i "0,/<p/ s_^_$thestring\n&_" file
echo "${thestring}" | sed s'@<p>this is@blah blah <p>this is@'

If you want to get a specific instance of " 如果要获取“

", just add a bit more context for the search. ”,只需为搜索添加更多上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM