3


How do I make this:

    TextTextText
    start
    stuff
    stuff
    stuff
    end
    start
    stuff
    end
    TextTextText

Look like this:

    startstuffstuffstuffend
    startstuffend

with sed? I tried this:

    sed -e '/start/,/end/N; s/\n//'

but it did this:

    startstuff
    stuffstuff
    endstart
    stuff
    end

It's only every second line...

BadJoke
  • 147
  • 1
  • 1
  • 10

4 Answers4

4

You can try following command:

sed -n '/start/,/end/ H; $ { g; s/\n//g; s/\(end\)/\1\n/g; p }' infile

It avoids automatic printing (-n), saves all lines between the range start and end in the hold buffer (H), and when the whole file has been processed ($), first removes all newlines characters and then adds one after each end word.

It yields:

startstuffstuffstuffend
startstuffend
Birei
  • 35,723
  • 2
  • 77
  • 82
  • Thank you, I've been searching this for two days! – BadJoke Dec 02 '13 at 22:28
  • Actually, when i have more than 2 "start end" ranges it writes them together in 1 line... – BadJoke Dec 02 '13 at 22:38
  • @birei can you look this question http://stackoverflow.com/questions/25947391/delete-n-characters-from-line-range-in-text-file answer here works only in range, what to change to preserve outrange lines? – josifoski Sep 20 '14 at 10:45
0

You can use awk

awk '/start/ {f=1} f {printf $1} /end/ {f=0;print ""}' file
startstuffstuffstuffend
startstuffend

Or you can do

awk '/start/,/end/ {printf $1;if ($0~/end/) print ""}' file
startstuffstuffstuffend
startstuffend
Jotne
  • 40,548
  • 12
  • 51
  • 55
0
sed '/start/
   {
: again
   N
   s/End$/&/
   t clean
   b again
: clean
   s/\n//g
   }
' file

Concatenate also if there is not "End" but only a Start, but maybe you don't want this (problem also occur in other answer)

NeronLeVelu
  • 9,908
  • 1
  • 23
  • 43
0
sed -n '/start/{h;:l n;H;/^end$/!bl;x;s/\n//g;p}' input
perreal
  • 94,503
  • 21
  • 155
  • 181