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 2 Answers
Have you just run
$ echo $i | grep cat
> the cat is a crazyGrep 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 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.