Monday, 5 August 2019

Linux - How to insert line after match using sed

I was working on certain project last week where i need  to insert line after match in 100 of files in Linux or Unix operating system. I found that insert line after match using sed is easy. It was quite  successful for me ,so i thought i will share this on my blog.

Let’s take an example to understand it
We have a html file like below
$ cat test.html
<html>
<head>
<title>This is test</title>
</head>
<body>
This is test page
</body>
</html>
I need to enter certain text after like <body> in the file
we can achieve it using sed with append
sed -e ‘/<body>/a  Welcome everybody’ test.html
<html>
<head>
<title>This is test</title>
</head>
<body>
Welcome everybody
This is test page
</body>
</html>
if I need to enter certain text before  like <body> in the file
#sed -e ‘/<body>/i Welcome everybody’ test.html
<html>
<head>
<title>This is test</title>
</head>
Welcome everybody
<body>
This is test page
</body>
</html>
So far the above command just changes the output. File is not changed. If you want to change the file also
we can do with -i option
#sed -i -e ‘/<body>/a  Welcome everybody’ test.html
#cat test.html
<html>
<head>
<title>This is test</title>
</head>
<body>
Welcome everybody
This is test page
</body>
</html>
sed insert line after match
You can make these changes in multiple files using *  or giving pattern the file
sed -i -e ‘/<body>/a  Welcome everybody’ *.html
Hope you like this short article on sed. Please do let me know your feedback

0 comments:

Post a Comment