To read specific path string from generation of curl result(SED/AWK/Grep)

Viewed 118

I am trying to read specific path(/opt/links/stances/2) from where I pulled out result using curl command.

Curl command:-

curl -s http://localhost:8080/stances/1/Dirs 

Result from above command:-

{"LocalWorkingDir":"/opt/links/stances/1","Workers":[{"WorkerInstanceID":2,"WorkerHostname":"yolo.automation.local","WorkerInstanceRunDir":"/opt/links/stances/2"}]}

command i am trying to read /opt/links/stances/2 from generated output :-

curl -s http://localhost:8080/stances/1/Dirs |  sed 's|$1|" "|' | awk '{print $1}'

I am ending up with no result. Please help me with command to read the path(/opt/links/stances/2). thanks in advance.

2 Answers

Since OP can't install jq, following could be tried with shown samples. But this could not be full fledge, this is completely as per shown samples only.

awk 'match($0,/"WorkerInstanceRunDir":"[^"]*"}/){print substr($0,RSTART+24,RLENGTH-26)}' Input_file

Explanation: Using match function to match regex "WorkerInstanceRunDir":"[^"]*"}, which will match everything from "WorkerInstanceRunDir till next occurrence of " followed by } then printing sub string starting from RSTART+24 till value of RLENGTH-26 here.

OR try setting field separators as per shown samples only.

awk -F'"|}' '$(NF-5)=="WorkerInstanceRunDir"{print $(NF-3)}' Input_file

If you have gnu grep then you can use a PCRE regex like this:

curl -s http://localhost:8080/stances/1/Dirs | 
grep -oP '"WorkerInstanceRunDir":"\K[^"]+'

/opt/links/stances/2

Details:

  • "WorkerInstanceRunDir":": Match literal text "WorkerInstanceRunDir":"
  • \K: Reset matched info
  • [^"]+: Match 1+ non-" characters

If you don't have gnu grep installed then use this sed:

curl -s http://localhost:8080/stances/1/Dirs |
sed -E 's/.*"WorkerInstanceRunDir":"([^"]+).*/\1/'
Related