Lin Ma
Lin Ma

Reputation: 10139

a weird string match issue using $ and grep

Got lost why add another , in the match pattern, it cannot match anything? What I want to achieve is to extract value for Foo in each record, i.e. 123, 234 and 345.

grep -o $"Foo*" grepdebugtest.txt
Foo
Foo
Foo

grep -o $"Foo*," grepdebugtest.txt

(match nothing)

cat grepdebugtest.txt
{"Foo":123,"Goo":456}{"Foo":234,"Goo":567}{"Foo":345,"Goo":678}

thanks in advance, Lin

Upvotes: 0

Views: 31

Answers (2)

glenn jackman
glenn jackman

Reputation: 246942

Use a JSON parser on JSON data:

jq '.Foo' <<END
{"Foo":123,"Goo":456}{"Foo":234,"Goo":567}{"Foo":345,"Goo":678}
END
123
234
345

Upvotes: 1

mikyra
mikyra

Reputation: 10367

The * operator in grep is different from the globbing operator used in the shell.

In grep * means zero or more repetitions of the previous character. Your pattern Foo*, matches Foo, Foooooo, and even Fo, but never Foo":123,.

To get the equivalent of the shell globbing operator you have to use .* in grep. Meaning zero or more repetitions of any character (. being the operator for any character)

Note, that taking this approach most probably you still don't match, what you are looking for, as grep will match greedy and take {"Foo":123,"Goo":456}{"Foo":234,"Goo":567}{"Foo":345, as match for Foo.*.

You might want to circumvent that problem matching with something like Foo[^,]*, instead.

Also note, that in case it isn't a typo anyways the $ in the command line given is quite useless and the command the same as grep -o "Foo*" grepdebugtest.txt

Upvotes: 1

Related Questions