1

So, following are the commands are I ran:

$ ~/Documents: touch ball.txt bool-txt bowl.txt bull.txt
$ ~/Documents: ls . | grep b..l\.txt
ball.txt
bool-txt
bowl.txt
bull.txt

I wasn't expecting bool-txt to be present in the output, because I have escaped the dot but its still not considering it a literal dot. Where am I going wrong?

3
  • that might be shell escaping, try putting it in a string
    – qwr
    Jun 27, 2021 at 8:50
  • also in general parsing ls is error prone, but probably not relevant to this question
    – qwr
    Jun 27, 2021 at 8:51
  • 1
    Yeah this ls . | grep b..l\\.txt works and also this ls . | b..l"\.".txt. Is this what you meant? Could you explain mean what is happening here or point me to relevant resources. @qwr Jun 27, 2021 at 8:53

1 Answer 1

5

I'm sure this is a duplicate of some question but I can't find it. On Unix SE https://unix.stackexchange.com/questions/583428/why-do-i-have-to-quote-an-escaped-character-in-a-regular-expression-for-grep-bu

When you use grep b..l\.txt, the shell converts \. into . so grep receives b..l.txt, then it interprets . as any character.

To prevent this, the easiest method is giving grep a string like grep 'b..l\.txt', then the shell won't escape the dot. Note that single quotes and double quotes do different things in bash but that doesn't matter in this case. Alternatively, use double backslash so the shell escapes the backslash as a literal character and grep correctly receives \..

2

Not the answer you're looking for? Browse other questions tagged .