Tiến Mạnh
Tiến Mạnh

Reputation: 117

Nested command and pipe command in shell script

I'm trying a few tests, in a shell script as below:

line="100:xx"
echo "$line" | grep -Po \\d+

result: 100

but,

line="100:xx"
echo `echo "$line" | grep -Po \\d+`

result is empty

Why?

Upvotes: 3

Views: 4063

Answers (2)

glenn jackman
glenn jackman

Reputation: 246837

Because backticks allow expansions like double quoted strings, one of your backslashes is being eaten too soon:

$ echo `echo "$line" | grep -Po \\d+ | cat`

$ echo `echo "$line" | grep -Po \\\d+`
100

That being said, just quote the regex

$ echo `echo "$line" | grep -Po '\d+'`
100

Upvotes: 5

Jahid
Jahid

Reputation: 22428

You can do this too:

echo $(echo "$line" | grep -Po \\d+)

to avoid your backslash being get eaten.

Upvotes: 2

Related Questions