0

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

Klimaat
  • 900
  • 12
  • 16
Harish
  • 13
  • 1
  • 3

6 Answers6

2

With sed you can turn off printing lines by default with -n and display lines with p. Using this information will show the solution

sed '/Samsung/p' yourfile
# Or, when you want to match the whole line
sed '/^Samsung$/p' yourfile
Walter A
  • 19,067
  • 2
  • 23
  • 43
2

To copy the entire line matching pattern, and to past it on the new line, right after that:

sed -i $'s/.*Samsung.*/&\\\n&/' file

The output:

Apple
Samsung
Samsung
Nokia
HTC

To output the result to another file.

sed $'s/.*Samsung.*/&\\\n&/' file > anotherfile
0

For a file input.txt with the contents

Apple
Samsung
Nokia
HTC

You can do inline replacement a duplicate the lines 'Samsung' like this:

sed -i 's/\(Samsung\)/\1\n\1/' input.txt

The parentheses capture the word, then \1 puts it back twice with a newline in between.

Harald Nordgren
  • 11,693
  • 6
  • 41
  • 65
0

Use this sed:

sed $'s/Samsung/&\\\n&/' input.txt

Outputs:

Apple
Samsung
Samsung
Nokia
HTC

See also:

Community
  • 1
  • 1
codeforester
  • 39,467
  • 16
  • 112
  • 140
  • Hi codeforester, thank you for your help. I gave a very simple example as the data but in my case I have a pretty lengthy line and it is not convenient to type the entire line each as I have to do this multiple times in my file. I was thinking to use grep, match the pattern, and then copy the entire line. Any thoughts? – Harish Mar 02 '17 at 22:41
  • Or this sed: `sed '/Samsung/ {h;G}' file` – glenn jackman Mar 03 '17 at 02:05
0

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
potong
  • 55,640
  • 6
  • 51
  • 83
0

For completeness:

awk '/Samsung/ {print}; {print}' file
perl -pe 'print if /Samsung/' file
glenn jackman
  • 238,783
  • 38
  • 220
  • 352