3

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?

4
  • is echo "$line" displaying the correct value? How about: line="100:xx" echo `echo "$line" | grep -Po \\d+` Commented Apr 27, 2015 at 9:25
  • 1
    Because you are using backticks instead of $() and they suck. Commented Apr 27, 2015 at 9:25
  • 2
    It's in the escaping of the backslash. Try echo `echo "$line" | grep -Po \\\\d+` or echo `echo "$line" | grep -Po '\\d+'` (But do switch to $(), backticks have been deprecated for a long time.) Commented Apr 27, 2015 at 9:25
  • thank everybody, way of @Biffen working correct for me Commented Apr 27, 2015 at 9:28

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

Using single quotes around the regex is the way to go.
2

You can do this too:

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

to avoid your backslash being get eaten.

2 Comments

Really? Backticks have better results than nested POSIX with pipes.
@Sandburg : Stop using backticks and start using $() instead. This is the new standard...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.