azilinha azilinha - 5 months ago 7
Bash Question

sed print more than one matches in a line

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

${cat.mouse.dog}
bird://localhost:${xfire.port}/${plfservice.url}
bird://localhost:${xfire.port}/${spkservice.synch.url}
bird://localhost:${xfire.port}/${spkservice.asynch.request.url}
${soabp.protocol}://${hpc.reward113.host}:${hpc.reward113.port}
${configtool.store.folder}/config/hpctemplates.htb


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:

cat.mouse.dog
xfire.port plfservice.url
xfire.port spkservice.synch.url
xfire.port spkservice.asynch.request.url
soabp.protocol hpc.reward113.host hpc.reward113.port
configtool.store.folder


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

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.

Comments