Piping commands in $()

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;

Jeremy

Posted 2017-02-15T19:08:48.627

Reputation: 31

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

Answers

1

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

Matt Clark

Posted 2017-02-15T19:08:48.627

Reputation: 1 819

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.

Spiff

Posted 2017-02-15T19:08:48.627

Reputation: 84 656