Monday, January 31, 2022

[SOLVED] How to copy an entire line which matches the string and paste right after it?

Issue

I am trying to search for a particular line in a file using grep command and I am successful doing that. Now I want to copy the entire line to a new line right after the original line. In other words, the original line should be followed by the new line with same content.

For example: Original data:

Apple 

Samsung

Nokia

HTC

Say if I want the new data to look like

Apple

Samsung

Samsung

Nokia

HTC

I tried grep and pipe with sed and I failed. Can anyone please help me with this?

Thanks


Solution

This might work for you (GNU sed):

sed '/pattern/H;//G' file

If the pattern can occur more than once:

sed 'x;z;x;/pattern/H;//G' file


Answered By - potong
Answer Checked By - Pedro (WPSolving Volunteer)