51

I am trying to use ER (Extended Regular Expressions) with ls like ls .+\..+.

I am trying to print all files which contains an extension (I know I could have used ls *.*, but I wanted to try using ER).

When I run that code I get this error: ls: .+..+: No such file or directory.

Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
Lucas Rezende
  • 2,516
  • 8
  • 25
  • 34

2 Answers2

111

You are confusing regular expression with shell globbing. If you want to use regular expression to match file names you could do:

$ ls | egrep '.+\..+'
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
  • 2
    Got it. So, first of all I have to check if what I am trying to use accepts RE. – Lucas Rezende Mar 11 '13 at 18:39
  • 3
    If the pattern can't be matched with `globbing` alone then you will have to use an alternative method. *F.Y.I* the tool `find` supports regexp matching. – Chris Seymour Mar 11 '13 at 18:42
  • `ls -f` would be probably faster if the list of files is very long. – rapto Oct 29 '18 at 08:37
  • `shellcheck` shows "Use find instead of ls to better handle non-alphanumeric filenames. See [SC2012](https://github.com/koalaman/shellcheck/wiki/SC2012)." for `ls` and "egrep is non-standard and deprecated. Use grep -E instead. See [SC2196](https://github.com/koalaman/shellcheck/wiki/SC2196)." for `egrep`. – lisymcaydnlb Jun 12 '21 at 20:52
5

You don't say what shell you are using, but they generally don't support regular expressions that way, although there are common *nix CLI tools (grep, sed, etc) that do.

What shells like bash do support is globbing, which uses some similiar characters (eg, *) but is not the same thing.

Newer versions of bash do have a regular expression operator, =~:

for x in `ls`; do 
    if [[ $x =~ .+\..* ]]; then 
        echo $x; 
    fi; 
done
CodeClown42
  • 11,194
  • 1
  • 32
  • 67
  • 1
    Cool! I have never heard about it! :) So it is only use `=~` and the interpreter will understand that what I am trying to match is a RE? – Lucas Rezende Mar 11 '13 at 18:45
  • 3
    You have to use it in the context of a *test*, I believe with double brackets, so for this specific case piping through (e)grep is much more straightforward. But it is useful to know about. – CodeClown42 Mar 11 '13 at 18:47
  • This is specifically a bash comparison operator, which is why it can only be used in tests. Just mentionign this for clarity. Very useful tool. – bikemule Jul 13 '16 at 05:41