Grep fails to find sequence after assign to variable

1

I run:

awk -F ',' '{print $2}' data.dat | sort | uniq |  tr '\n' ',' | grep "*)>nS4XkrlH  @XUL"

and the sequence is located in results.

Then I run

b=`awk -F ',' '{print $2}' data.dat | sort | uniq |  tr '\n' ','`
echo $b | grep "*)>nS4XkrlH  @XUL"

but no result is returned.

Does anyone have any ideas on why this happens?

Thanks for any help.

dr.doom

Posted 2014-12-14T03:15:00.183

Reputation: 13

Answers

0

The key key difference between those two command sequences is that the second contains echo $b which performs shell word splitting. To make the second command sequence run the same as the first, replace:

echo $b | grep "*)>nS4XkrlH  @XUL"

with:

echo "$b" | grep "*)>nS4XkrlH  @XUL"

Word Splitting

Observe how spaces are treated in these two echo statements:

$ b="a   b c"
$ echo "$b"
a   b c
$ echo $b
a b c

Without the double-quotes, the shell performs word-splitting on the arguments to echo. This means that all consecutive whitespace is condensed to a single space. With double-quotes, word splitting is suppressed and the whitespace is preserved.

Word Splitting and a grep Pattern with Multiple Spaces

Your grep pattern contains two consecutive spaces. Unless the argument to echo is in double-quotes, the output of echo will not have those two spaces and no match will be found. Observe:

$ b="*)>nS4XkrlH  @XUL"
$ echo $b | grep "*)>nS4XkrlH  @XUL"
$ echo "$b" | grep "*)>nS4XkrlH  @XUL"
*)>nS4XkrlH  @XUL

The first grep does not match on anything but the second does. The difference is the shell's word splitting.

John1024

Posted 2014-12-14T03:15:00.183

Reputation: 13 893

You are correct! The explanation was very good. – dr.doom – 2014-12-14T15:00:50.953