18

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

3 Answers 3

18

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.

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

string ~ /regexp/ will check if the regexp (which is disk here) matches the given string, which is variable a in this case. The && operator is used here to combine two conditions, only if the first condition /fcs/ and the second condition a ~ /disk/ are both true, the print will execute.

0
8

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.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .