Run `ls` recursively with wildcards

I'm trying to find all the project files of a particular file type with:

ls -ltR *.mb

I know there are the files I want in several folders, but I get no results back. What did I do wrong?

2 Answers

ls doesn't match patterns. It simply lists the files or folders in the input arguments. *.mb is expanded by the shell before passing to ls, therefore if there are no files named *.mb in the current directory, nothing will be output, otherwise only files in the current directory will be output

The standard way to list files recursively is to use find

find . -name '*.mb' -type f -printf "%-.22T+ %M %n %-8u %-8g %8s %Tx %.8TX %p\n" | sort | cut -f 2- -d ' '

This way you can customize the output list format as you want. See: List files by last edited date


An alternative way is to use globstar which can be enabled with shopt -s globstar

ls -ltR **/*.mb

The first **/ will match any arbitrary subdirectory paths. Then *.mb with match your files in those directories

  • globstar

    If set, the pattern ** used in a filename expansion context will match all files and zero or more directories and subdirectories. If the pattern is followed by a /, only directories and subdirectories match.

1

@phuclv has two good options. When I need to do similar, I typically pipe the output of ls to grep like this:

ls -ltR | grep .*\.mb

this sends the output of ls to the input of grep instead of outputting to stdout, and grep then outputs only the lines that contain at least one match for the regular expression.

The regex

.*\.mb

can be explained as:

.: match any character
*: preceding character or group should appear 0 or more times
\.mb: literally .mb
3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like