10

I wanted to list the content of a pwd and display only file starting with dot. I tried ls -a | grep ^\. but I cannot figure out why the output contains also the files which do not start with dot. For example:

Pictures
.pip
.pki
.profile
projects
Public

I know that I can achieve what I want with ls -ld .* I am just curious about this behaviour of grep which I can't explain.

Michael Mrozek
  • 93,103
  • 40
  • 240
  • 233
ps-aux
  • 311

3 Answers3

20

Quote the argument to grep, thus ls -a | grep '^\.'

The reason for this is that the shell handles \. and turns it back into plain ., which grep then treats as a single-character wildcard. If in doubt, always quote a string that contains (or might contain) a character that's special to the shell.

Chris Davies
  • 116,213
  • 16
  • 160
  • 287
  • Why does shell ignore ? – ps-aux Apr 05 '15 at 11:25
  • \ is an escape sequence which makes the shell to treat the following character as a literal one. In this grep ^\\., \ is treated by the shell as a single backslash and again the grep treats single backslash followed by the dot as literal dot. – Avinash Raj Apr 05 '15 at 11:28
11

You need to put the grep regex inside quotes.

ls -a | grep '^\.'

Note: Don't parse the output of ls command.

Avinash Raj
  • 3,703
0

If you execute cmd ls -a | grep ^\. then grep do not consider "\" as a special character and meaning of "." do not get escaped.

When we use cmd ls -a | grep "^\." then grep considers "\" as a special character and meaning of "." gets escaped. It will give you a result as expected.

If you want to use grep cmd without quotes then you should escape "\" character also. You can have expected result without double quotes by following command. ls -a | grep ^\\.

For details about meaning of special characters in Regex, refer following link. http://www.regular-expressions.info/quickstart.html

AVJ
  • 505