azilinha azilinha - 1 year ago 68
Bash Question

sed print more than one matches in a line

I have a file, including some strings and variables, like:


I want to print all the strings between "{}". In some lines there are more than one such string and in this case they should remain in the same line. The output should be:
xfire.port plfservice.url
xfire.port spkservice.synch.url
xfire.port spkservice.asynch.request.url
soabp.protocol hpc.reward113.port

I tried the following:

sed -n 's/.*{//;s/}.*//p' filename

but it printed only the last occurrence of each line. How can I get all the occurrences, remaining in the same line, as in the original file?

Answer Source

If you're not against awk, you can try the following:

 awk -v RS='{|}' -v ORS=' ' '/\n/{printf "\n"} (NR+1)%2' file

The record separator RS is set to either { or }. This splits the wanted pattern from the rest.

The script then displays 1 record out of 2 with the statement (NR+1)%2.

In order to keep the alignment as expected, the output record separator is set to a space ORS=' ' and everytime a newline is encountered this statement /\n/{printf "\n"} inserts one.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download