A script must be written to extract and return a string value from a file. This must be done only after a match is found in the file for the given pattern.



This text is the sub part of a big log file and also many instances of this with "id":"some value" could occur. I need to return that 'some value' portion every time and from a lot of files in that directory.

I think sed utility in Unix helps here, but I couldn't figure out ts exact usage. Would be glad if somebody could help.

  • is this json data? if so, use jq or jsonpipe or a language with json-parsing libraries (e.g. perl or python). – cas Jun 11 '16 at 4:06

You're not clear on whether you want just the first : separated value or the whole remainder of the line after the "id" tag.

The former is:

sed -nre 's/^"id":"([^:]*):.*/\1/p' <file>

The latter is:

sed -nre 's/^"id":(.*)/\1/p' <file>

Note the switches are important. -n ensures that nothing is printed (with the p tail printing those lines that do match). -r enables extended regular expression parsing so things like brackets don't have to be escaped.

  • Brackets never have to be escaped. Also -E is more portable than -r and does the same thing. – Wildcard Jun 11 '16 at 0:16

sed 's/"id":"\([^"]*\)"/\1/g'

Extracts the value if you pipe it in via stdin

  • 3
    Please explain your answer. Bare sed scripts are hard to understand, especially for a questioner who's not familiar with sed. – Andrew Schulman May 1 '15 at 11:58
  • This does not "extract the value", it replaces the occurrence of the pattern "id":"(...)" with the part captured inside the parentheses, as in, piping text like Alice: hello\n"id":"boom"\nBob: hi! will come out of sed like Alice: hello\nboom\nBob: hi!. – amn Aug 4 '16 at 8:32

Your Answer

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