I have a unformatted file returned form a SQL query, from which I need to find a regex match and extract a numeric string that follows. The number is enclosed between two double quotes. Note there could be more then one occurrence of a match per line. There are other special characters in the file which should be ignored. Here is the example file:

{ "_id" : "66941672632817171654", "title" : "Some Name (Central)", "stationNameAssoc" : [ { "stationId" : "6248915749115539177", "stationName" : "Default" } ] }
{ "_id" : "4455677484649934117", "title" : "Some Name (Mountain)", "stationNameAssoc" : [ { "stationId" : "7597999415247634177", "stationName" : "Default" } ] }

From this, I want to extract a numeric after "stationId" excluding quotes e.g. 7597999415247634177. How would you do this using awk or bash? thanks

  • 2
    Looks like json; is it? – Jeff Schaller Dec 12 '16 at 22:40
  • Use jshon or another json parser... – jasonwryan Dec 12 '16 at 22:41

using a Json tool called json (https://github.com/trentm/json)

$ json -ga 'stationNameAssoc.[0].stationId' < input

or use it step by step:

cat input | json -ga 'stationNameAssoc' | json -ga stationId

documentation in: http://trentm.com/json/

if not installed:

install node
and sudo npm install -g json

Another JSON parser solution, using jq:

$ jq -r '.stationNameAssoc[0].stationId' data.json

It simple fetches the values of the stationId entry of the first (and only) array item in each stationNameAssoc array.

awk -F\" '{for(i=1;i<=NF;i++)if($i~/Id/){print $(i+2);next}}' input.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.