azilinha
azilinha

Reputation: 25

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?

Upvotes: 2

Views: 89

Answers (2)

oliv
oliv

Reputation: 13249

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.

Upvotes: 1

potong
potong

Reputation: 58440

This might work for you (GNU sed):

sed -n 's/${/\n/g;T;s/[^\n]*\n\([^}]*\)}[^\n]*/\1 /g;s/ $//p' file

Replace all ${ by newlines and if there are non then move on as there is nothing to process. If there are newlines then remove non-newline characters to the left and non-newline characters to the right of the next } globally. To finish off remove the extra space introduced in the RHS of the global substitution.

Upvotes: 2

Related Questions