9

I have a text file, where records are split on two lines. I would like to put them on one line. The records look something like this:

2013-07-29
 apt-get install git
2013-07-29
 apt-get install rsync
2013-07-31
 apt-get install nmap
2013-08-02
 apt-get install cifs-utils
2013-08-05
 apt-get install telnet

I would like to get the following:

2013-07-29 apt-get install git
2013-07-29 apt-get install rsync
2013-07-31 apt-get install nmap
2013-08-02 apt-get install cifs-utils
2013-08-05 apt-get install telnet

I tried with sed, but I am unable to match two lines. Is there some trick in sed, or is there some better tool ?

  • It seems less like you want to match two lines, and more you want to join the line after you find a match. Yes? – kurtm Oct 7 '13 at 15:11
12
sed 'N;s/\n/ /'
  • N joins next input line to the pattern space
  • s/\n/ / replaces the new-line that separates the lines with a space.

or:

sed -n 'N;s/\n/ /;/regex/p'
  • -n disables automatic printing of pattern space as last command
  • /regex/p prints lines matching regex

Use the g modifier for the substitutions in case you are joining more than two lines, e.g. N;N;N;s/\n/ /g.

  • Thank you for the great explanation instead of just copypasta. – g33kz0r Dec 15 '16 at 17:53
6

It seems that the apt-get lines have a preceding whitespace. Saying:

sed -e :a -e '$!N;s/\n / /;ta' -e 'P;D' inputfile

should produce the desired result.

Alternatively, you can also use paste:

paste -d' ' - - < inputfile

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.