2

I have a JSON like below coming from curl command and it is present in a output.txt file. I want to retreive the JIRA status, here it is "In Progress"

{
     "self": "https://jira.com/jira/rest/api/2/issue/1",
     "fields": {
        "status": {
            "self": "https://jira.com/jira/rest/api/2/status/10170",
            "description": "", 
            "name": "In Progress",
            "id": "10170" 
        }
    }
}

I have a restriction to use only sed . I tried like below it does not work . I am not sure how to navigate to the name value. can you please suggest to print JIRA status

sed -n 's|.*"fields":{"status":{"name":"\([^"]*\)".*|\1|p'  output.txt
6
  • jq seems like a better fit for dealing with JSON (stedolan.github.io/jq) Commented Jun 4, 2021 at 11:22
  • The docker image does not work with jq unfortunately. I cannot change the docker right now and it works only with sed Commented Jun 4, 2021 at 11:24
  • 2
    How about sed -nE '/"name":/ s/.*"(.+)".*/\1/p' or awk -F'"' '/"name":/{print $4}' assuming only one line will match when searching for "name": Commented Jun 4, 2021 at 11:29
  • 1
    Try sed -n 's/^[[:space:]]*"name": "\(.*\)",/\1/p' file, see ideone.com/VuKvrY. Do you really need to check for fields":{"status" presence? Commented Jun 4, 2021 at 11:32
  • 1
    @WiktorStribiżew - Not really Commented Jun 4, 2021 at 11:36

1 Answer 1

2

You can use

sed -n 's/^[[:space:]]*"name": "\(.*\)",/\1/p' output.txt
# With GNU sed:
sed -n 's/^\s*"name":\s*"\(.*\)",/\1/p' output.txt

See the online demo

Details:

  • n - suppresses default line output
  • ^\s*"name":\s*"\(.*\)", - matches
    • ^ - start of string
    • \s* - zero or more whitespaces
    • "name": - a literal string
    • \s* - zero or more whitespaces
    • " - a " char
    • \(.*\) - a POSIX BRE capturing group matching any text up to
    • ", - the last occurrence of ", (they are at the end of the targeted line anyway).
  • \1 - replaces the whole match with Group 1 value
  • p - only prints the replacement result.

With a GNU sed, you can also use the -z option to read the file as a single string and then use a more specific pattern:

sed -z 's/.*"fields":\s*{\s*"status": {.*\s*name": "\([^"]*\)".*/\1/' output.txt

See this online demo.

It does something very close to this demo.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.