[英]Linux add new line before and after a matched pattern
I want to put newline before "< script" and after < /script> tags in an HTML file. 我想在HTML文件中的“ <脚本”之前和</ script>标记之后放置换行符。
sed 's/<script/\'$'\n/g'
I tried that one but it deleted "script" tags. 我尝试了一个,但是删除了“脚本”标签。
Sample input: 输入样例:
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>JavaScript Ders 2</title> <script type="text/javascript" src="script.js" language="javascript"></script> <script type="text/javascript" src="script.js" language="javascript"></script> <script></script> </head><body> <script type="text/javascript" src="script.js" language="javascript"></script> </body></html>
Sample output: 样本输出:
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>JavaScript Ders 2</title>
<script type="text/javascript" src="script.js" language="javascript">
</script>
<script type="text/javascript" src="script.js" language="javascript">
</script>
<script>
</script>
</head><body>
<script type="text/javascript" src="script.js" language="javascript">
</script>
</body></html>
What I have to do? 我该怎么办?
Thanks 谢谢
Since you haven't posted any samples so couldn't test it, could you please try following and let me know then. 由于您尚未发布任何示例,因此无法对其进行测试,因此,请您可以尝试按照以下说明告诉我。
sed 's/<script>/\n&/;s/<\/script>/&\n/' Input_file
Let's say following is Input_file: 假设以下是Input_file:
cat Input_file
<script>
fewvfewvvew
</script>
abcd
Then after executing code we will get following output then. 然后,在执行代码之后,我们将获得以下输出。
<script>
fewvfewvvew
</script>
abcd
I'm assuming you're just doing this to make it easier to read, rather than attempting to format HTML using sed... 我假设您只是这样做以使其更易于阅读,而不是尝试使用sed格式化HTML ...
To add newlines before <script
and </script
(assuming that your version of sed understands \\n
): 要在
<script
和</script
之前添加换行符(假设您的sed版本理解\\n
):
sed -E 's|</?script|\n&|g' file
Match </?script
( /?
makes the /
optional) and replace with a newline, followed by the full match &
. 匹配
</?script
( /?
使/
可选)并替换为换行符,后跟完整匹配&
。
It doesn't quite match the output in your question since it looks like you want to put each opening/closing <script>
tag on its own line, rather than just insert lines: 它与您问题中的输出不太匹配,因为您似乎想将每个开始/结束
<script>
标记放在自己的行上,而不是仅插入行:
$ sed -E 's|</?script|\n&|g' file
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>JavaScript Ders 2</title>
<script type="text/javascript" src="script.js" language="javascript">
</script>
<script type="text/javascript" src="script.js" language="javascript">
</script>
<script>
</script> </head><body>
<script type="text/javascript" src="script.js" language="javascript">
</script> </body></html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.