Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge lines between two patterns using sed

Tags:

grep

sed

I have an output file that looks like this:

HEADER 1:
server1 server2 server3
server4 server5 server6
server7 server8 server9
HEADER 2:

HEADER 1:
server10 server11 server12
server13 server14 server15
server16 server17 server18
HEADER 2:

I need to merge everything between the two headers so the updated output file looks like this:

HEADER 1:
server1 server2 server3 server4 server5 server6 server7 server8 server9
HEADER 2:

HEADER 1:
server10 server11 server12 server13 server14 server15 server16 server17 server18
HEADER 2:

The header names always remain constant.

I'm using UnxUtils in Windows, so unfortunately I don't have awk to do the manipulation. How do I go about it using sed?

like image 840
jplusc Avatar asked Nov 20 '13 11:11

jplusc


People also ask

How do you join two lines using sed?

Add a newline to the pattern space, then append the next line of input to the pattern space. If there is no more input then sed exits without processing any more commands.

How do I combine multiple lines in one line?

Alternatively, you can also use shortcut “Ctrl” + “H” to open the dialog box. Click the “Replace” tab, then keep the “Replace with” field empty, as you need to replace the ^p with empty text. Finally, click “Replace All” button to perform the replace operation.

How to concatenate lines in linux?

To merge lines of files, we use the paste command in the Linux system. The paste command is used to combine files horizontally by outputting lines consisting of the sequentially corresponding lines from each FILE, separated by TABs to the standard output.


1 Answers

Using sed:

sed '/HEADER 1/{n;:l N;/HEADER 2/b; s/\n//; bl}' input
  • n skips/prints the current line (HEADER 1), clears buffer
  • l is a label for looping (goto label)
  • N adds (appends) lines to buffer (preserving newlines)
  • /HEADER 2/b, where b is branch (without the label, it is break), break out when HEADER2 is seen
  • s/\n// removes the newlines in the buffer
  • bl jumps back to label l
like image 72
perreal Avatar answered Oct 03 '22 20:10

perreal