2
This is an example of a shell script I'm trying to run, but instead of printing out the grep'ed result, it prints the whole string. Is it not possible to pipe when in $()
?
i="the cat is a crazy"; word=$( echo $i | grep cat); echo $word;
2
This is an example of a shell script I'm trying to run, but instead of printing out the grep'ed result, it prints the whole string. Is it not possible to pipe when in $()
?
i="the cat is a crazy"; word=$( echo $i | grep cat); echo $word;
1
Have you just run
$ echo $i | grep cat
> the cat is a crazy
Grep print lines matching a pattern
You want to use -
-o, --only-matching
Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.
$ i="the cat is a crazy"; word=$( echo $i | grep -o cat ); echo $word;
> cat
0
You want grep -o
to get just a single word out of a line. grep
’s default behavior is to print out the whole line where a match is found.
To answer the question in a strict sense: yes it is possible to pipe with
$()
, as it is a fully functional subshell. The thing is,grep
doesn't exactly do what you expect it to. It prints lines containing the expression, which in this case is the whole string. – mtak – 2017-10-12T06:39:42.000