0

My file is in JSON format is looks like this:

name: Tom species: mouse name: Stu species: cat name: Carter species: Dog

I have a file that is one long string, and I would like to extract only the names from this list. So the desired output is something like this:

Tom Stu Carter

I've had a lot of failed attempts at sed, for example

cat alphabet | sed 's/^.*name: \(.*\) species*/\1/g'

Output:

Tom species: mouse name: Stu species: cat name: Carter : Dog

I have a lot of really big files I'd like to do this with so if there is an efficient way to go about this that would be great

  • 4
    Your sample text is not in JSON format. – Satō Katsura Sep 9 '16 at 16:49
1

If your input actually was JSON, then a JSON tool should be used.

The format that it is in appears to be suitable for awk:

$ awk '{for (i=2;i<=NF;i++) if ($(i-1)=="name:") print $i}' file
Tom
Stu
Carter

This looks at every field i on a line, starting with the second field. If the previous field was name:, then it prints the current field.

To keep all the output on one line (without a trailing blank):

$ awk '{for (i=2;i<=NF;i++) if ($(i-1)=="name:") {printf "%s%s", f,$i; f=" "}; print""}' file
Tom Stu Carter
1

With GNU grep:

grep -Po 'name: \K[^ ]*' file | tr '\n' ' '

or with GNU sed:

sed -r 's/name: ([^ ]*) species: [^ ]*/\1/g' file

Output:

Tom Stu Carter

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.