-2

I have a file that consists of two repeatedly occurring lines.

line1
     line2
line1
     line2
line1
     line2

I want to merge them so that the output file would look like:

line1 line2
line1 line2
line1 line2

Unfortunately I didn't succeed. In notepad++ I could do something like:

search: (line1)(\r\n)
replace: \1

Here I wanted to do the same but this:

sed -E 's/(line1)(\n)/\1/' my_file

doesn't work

anubhava
  • 761,203
  • 64
  • 569
  • 643
Z.Szymon
  • 337
  • 1
  • 13

2 Answers2

1

You can use paste and tr for this:

cat file | paste -d" " - - | tr -s ' '

line1 line2
line1 line2
line1 line2
Paul Dawson
  • 1,332
  • 14
  • 27
  • This one merged only first two lines. The rest remained unchanged. Nevertheless thank you. – Z.Szymon Jul 22 '19 at 13:53
  • 1
    How do you mean? It will go through the whole file and print alternate lines on one line. You could use `paste -d" " - - -` will print every 3 lines onto one and so forth. – Paul Dawson Jul 22 '19 at 13:56
  • Ok than it works. Is there any way to not specify dashes? Can't it go to the end of the file itself? – Z.Szymon Jul 22 '19 at 13:59
  • No, that's part of the command `- -` is 2 lines `- - -` is 3 lines `- - - -` is 4 lines etc. – Paul Dawson Jul 22 '19 at 14:01
  • 1
    Oh now I understand. It was working the whole time what I forgot to mention was that I had empty lines in between and hence I thought it was broken. Now I think that I like your answer the most. – Z.Szymon Jul 22 '19 at 14:04
1

sed doesn't match across the line. You may use perl in slurp mode:

perl -0777 -pe 's/(line1)\R+\h+/$1 /g' file

line1 line2
line1 line2
line1 line2
line1 line2
anubhava
  • 761,203
  • 64
  • 569
  • 643