hedleyyan hedleyyan - 1 year ago 52
Bash Question

How to use backreference multiple times?

dump.data as below:


I want to filer only the
info. e.g. After whatever process gives me this:


What comes to my mind is using backreference, i.e. sed:

sed 's|.*\("id":[0-9]*\).*\("value":[0-9]*\).*|\1,\2|' dump.data

which gives me this:


But how can I get all the id and value info?

Answer Source

Simplified version from other solutions already presented

$ perl -lne 'print join ",", /"[^"]+":\d+/g' dump.data 
  • "[^"]+":\d+ pattern to extract
  • join "," use , as separator to combine the extracted patterns

To capture only id and value

$ perl -lne 'print join ",", /"(?:id|value)":\d+/g' dump.data
  • (?:id|value) to restrict to only id or value, but in non-capturing group so that only the entire extracted text is passed onto join