[regex] Regular Expression usage with ls

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.

This question is related to regex ls glob

The answer is


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

$ ls | egrep '.+\..+'

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

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to ls

'ls' is not recognized as an internal or external command, operable program or batch file 'ls' in CMD on Windows is not recognized Count number of files within a directory in Linux? How do I assign ls to an array in Linux Bash? How can I list (ls) the 5 last modified files in a directory? Regular Expression usage with ls How to get file creation date/time in Bash/Debian? List of All Folders and Sub-folders Listing only directories using ls in Bash? How to create ls in windows command prompt?

Examples related to glob

How to loop over files in directory and change path and add suffix to filename glob exclude pattern Regular Expression usage with ls How can I search sub-folders using glob.glob module? Loop through all the files with a specific extension Deleting all files from a folder using PHP? Python glob multiple filetypes How to count the number of files in a directory using Python Get a filtered list of files in a directory How to use glob() to find files recursively?