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'


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

  • 5
    Your sample text is not in JSON format. Sep 9, 2016 at 16:49

2 Answers 2


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

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

With GNU grep:

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

or with GNU sed:

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


Tom Stu Carter

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .