How to search for all the files starting with the name "ABC" in a directory?
To complete existing answers:
ls
The default directory list utility ls
can be used in combination with the shell's wildcards . To search for all files with pattern abc
:
ls -d abc* # list all files starting with abc---
ls -d *abc* # list all files containing --abc--
ls -d *abc # list all files ending with --abc
Note that the file extension is relevant for the search results too.
tree
In case we need to list files in a directory tree we can also issue tree
to search for a given pattern like:
tree -P 'abc*' # list directory tree of file starting with abc---
tree -l 'def*' # exclude files starting with def---
In this case, tree
itself supports wildcards.
You can use find
command to search files with pattern
find . -type f -name "abc*"
The above command will search the file that starts with abc under the current working directory.
-name 'abc'
will list the files that are exact match. Eg: abc
You can also use
-iname
-regex
option with find
command to search filename using a pattern
There are many ways to do it, depending on exactly what you want to do with them. Generally, if you want to just list them, you can do it in a terminal using:
find | grep '^\./ABC'
... and replacing ABC
with your text.
To understand the command, let's break it down a bit:
find
lists all files under the current directory and its sub-directories; using it alone will just list everything there. Note thatfind
outputs each file or directory starting with./
, indicating that their path is relative to the current directory. Being aware of this is important because it means we will search for results starting with./ABC
and not justABC
.The pipe character
|
redirects the output of one command to another, in this case the output offind
is redirected togrep
. This is called piping.grep
takes the output and filters it using the given pattern,^\./ABC
.- Notice that the pattern is quoted with single quotes
' '
to prevent the shell from interpreting the special characters inside it.
- Notice that the pattern is quoted with single quotes
Now the pattern itself is written in a particular syntax called regular expression, or regex for short. Regex is an extremely powerful searching tool if you master it, and there are sites such as this which teach you about it in more depth, but note that
grep
is not a full-fledged regex engine and you can't do everything with it.For our purpose:
^
in regex matches the beginning of the string; this prevents it from matching the pattern if it doesn't occur in the beginning of the file name..
in regex has a special meaning too: it means "match any single character here". In case you want to use it as a literal dot, you'll have to "escape" it using a backslash\
before it. (Yeah, matching any character would be harmless in our case, but I did it for completeness' sake.)