简体   繁体   中英

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.

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:

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...

To add newlines before <script and </script (assuming that your version of sed understands \\n ):

sed -E 's|</?script|\n&|g' file

Match </?script ( /? makes the / optional) and replace with a newline, followed by the full match & .

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:

$ 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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