7

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
...
9

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.

7
$ awk '/fcs/ && a ~ /disk/ {print a","$0} {a=$0}' disk.out
disk0,fcs0
disk1,fcs1
6

If it's always in that format (one fcs for one disk, fcs always after disk), you could do without awk:

grep -F -e disk -e fcs file | paste -d , - -

Or:

awk '(/disk/ && ORS=",") || (/fcs/ && ORS=RS)' file

Though with awk, you may prefer a more legible approach as given by Martin or sp asic.

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.