Piping commands in $()

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 crazy

From the manual:

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

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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like