sed: insert word or text after match in middle of the line (search and append a string before or after match)

How to append a string after a match?

For eg I have a text line "This is not test" where I would like to insert "really" after matching "is"

Command:

echo "This is not test" |sed 's/<is>/& really/'
This is really not test

NOTE: Here since in the same line I had "is" twice i.e. once in "This" and another "is" so I have used < > to specifically look for "is" and nothing else

Similarly you can also append a text after "This" as shown below

Command:

echo "This is not test" |sed 's/<This>/& really/'
This really is not test

How to append a string before a match?

I will append "Really" before my match "this"

# echo "this is not test" |sed 's/<this>/Really &/'
Really this is not test

Another example

# echo "this is not test" |sed 's/<test>/some &/'
this is not some test

How to do "in place" replacement in a file?

This can be done using "-i" flag with sed command as shown in below example.
Command:

# sed -i 's/<is>/& not/' /tmp/filename

IMPORTANT NOTE:  Do not use in place replacement this unless you are very sure the command will not impact anything else, it is always recommended to use below command which will take a backup of the target file before doing the in place replacement

# sed -i.bak 's/<is>/& not/' /tmp/filename

1 thought on “sed: insert word or text after match in middle of the line (search and append a string before or after match)”

  1. pradeepm$ crontab -l
    */1 * * * * Server 1 check
    */1 * * * * Server 2 check
    */1 * * * * Server 3 check
    pradeepm$ crontab -l | sed '/^[^#].*Server 1 check/s/^/#/' | crontab -
    pradeepm$ crontab -l
    #*/1 * * * * Server 1 check
    */1 * * * * Server 2 check
    */1 * * * * Server 3 check
    pradeepm$ crontab -l | sed '/^#.*Server 1 check/s/^#//' | crontab -
    pradeepm$ crontab -l
    */1 * * * * Server 1 check
    */1 * * * * Server 2 check
    */1 * * * * Server 3 check

    Reply

Leave a Comment