Awk multiple pattern match and print in single line

awktext processing

I have the following file:

$ cat disk.out
disk0
fcs0
text
text
text
disk1
fcs1
text
text
text
text
...

What I am trying to achieve is match "disk" + "fcs" and then print the pair in one line, like this:

disk0,fcs0
disk1,fcs1
...

So I am matching "disk" and "fcs" with awk and changing the output record separator to ",".`

$ awk '/disk|fcs/' ORS="," disk.out
disk0,fcs0,disk1,fcs1,

The problem is, it will print all the matches on one line and with a trailing ,.
How can I print only per match in one line? Like this:

disk0,fcs0
disk1,fcs1
...

Best Answer

You have to save the "disk" line (without printing it) until you find the next "fcs" line:

awk '/disk/{ DISK=$0; next } /fcs/{ print DISK "," $0 }'

The problem with your approach is that it prints either line matching "disk" or "fcs", without combining those lines.

Edit: the script of sp asic is more robust, in that it ignores

disk3
text
fcs3

My script would happily print "disk3,fcs3" in this case.

Related Question