Home > Enterprise >  Sed & awk to replace string from JSON output
Sed & awk to replace string from JSON output

Time:10-21

I am executing below command to get particular string from json output , here I am grepping with string "uri" which prints all the required fields.

# curl -X GET --insecure -H "$(cat /token/.bearer_header)" http://localhost:3000/api/search?query=% |  sed -e 
's/[{}]/''/g' | awk -v RS=',"' -F: '/^uri/ {print $2}' 
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  2410    0  2410    0     0  40166      0 --:--:-- --:--:-- --:--:-- 40847
"ab/any-dashboard"
"ab/many-dashboard"
"ab/too-dashboard"
"ab/maximum-dashboard"
"ab/minimum-dashboard"

now I want to replace for example "ab/any-dashboard" to only any-dashboard, which means above command should print like below

any-dashboard
many-dashboard
too-dashboard
maximum-dashboard
minimum-dashboard

can anyone help me here I tried several things with sed but not getting exact result, and I dont have knowledge in JQ.

Regards, SAM

CodePudding user response:

This might work for you (GNU sed):

sed -nE 's#".*/(.*)"#\1#p' file

Turn off implicit printing -n, and turn on extended regexp -E (-r on some platforms).

Pattern match on the required string and replace it with the expected part and print the result.

N.B. The (...) in the LHS of the substitution command is called a back reference and can be recalled in the RHS. Also the use of # as an alternative separator rather than the usual / which is part of the match.

CodePudding user response:

If the awk statement below is at the end of the command line, try adding this gsub function and see if you get what you want:

Current:
awk -v RS=',"' -F: '/^uri/ {print $2}'

Change to:

awk -v RS=',"' -F: '/^uri/ {gsub("/","-",$2);print $2}'
  • Related