Categories
RHEL / CentOS

Sed – Insert Text before or after a string in a newline w/o TAB Space

SED is a very powerful utility which allows find and replace/insert text functionality. It should be used with Caution and is recommended to use dry-run before committing the changes. Below are the various commands for text manipulation.

Note:

\n = for newline

\t = for TAB space

Dry run = just remove ‘-i‘ form the below command

 Find the pattern and Insert text AFTER

# sed -i 's/.*search 1st Line.*/&\nInsert 2nd line/' file1

Output:

[[email protected] farooq.ahmed]# sed 's/.*search 1st Line.*/&\nInsert 2nd line/' file1
search 1st Line
Insert 2nd line

Find the pattern and Insert text AFTER (give TAB space)

# sed -i 's/.*search 1st Line.*/&\n\tInsert 2nd line with TAB Space/' file1

Output:

[[email protected] farooq.ahmed]# sed 's/.*search 1st Line.*/&\n\tInsert 2nd line with TAB Space/' file1
search 1st Line
        Insert 2nd line with TAB Space

Find the pattern and insert text BEFORE

# sed -i 's/.*search 1st Line.*/Insert 2nd line on top\n&/' file1

Output:

[[email protected] farooq.ahmed]# sed 's/.*search 1st Line.*/Insert 2nd line on top\n&/' file1
Insert 2nd line on top
search 1st Line

Find the pattern and insert Text BEFORE (give TAB space)

# sed -i 's/.*search 1st Line.*/Insert 2nd line on top w TAB Space\n\t&/' file1

Output:

[[email protected] farooq.ahmed]# sed 's/.*search 1st Line.*/Insert 2nd line on top w TAB Space\n\t&/' file1
Insert 2nd line on top w TAB Space
        search 1st Line

If any issues, do Contact us and we will help you out.

Leave a Reply

Your email address will not be published.