Ubuntu – How to find a word and add text after it in a .txt file

command linetext processing

How can I find a word (e.g. "/dn") in a text file and add on the next line another word (e.g. "/period")?

I'd like to execute it using MS DOS.

I mean this "/dn" (after /dn is space) is one word (not a fragment of the text, but the whole word–after /dn can be other word on the same line) which I want to find and then after it on the next new line, not replacing the other lines and other words. I mean create a new line between already existing lines.

For example, if I have this input file:

/dn
/name

I want this output:

/dn
/period
/name

and "/" symbol should be with dn, not without it.

Best Answer

1. Using sed append

If you want a completely new line with the word /period after each line containing /dn then use sed append:

sed '\:\dn:a/period' filename

the output for your sample would be:

/dn
/period
/name

1. Notes

  • :\dn: search for \dn
  • a/period append /period to the next line (a new line).

2. Search and append to the end of next line

If you want the /period at the end of the next line then use it like this:

sed ':/dn: { N; s:$:/period: }' filename

Here is a sample input:

/dn
/name

and the output:

/dn
/name /period

2. Notes

First we are searching for lines with /dn, then we add the /period at the end of ($) next line (N;).