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"


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


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.

# 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