How to list files based on matching only part of their filename?
I have many files in a folder for example
Kiran.txt
Kiran1.txt
Kiran221.txt
Kiran144.txt
Time.csv
Timer.csv
Timer2.csv
Timer444.csv
Timer266.csv
Account.sh
Account3.sh
Account3333.sh
Account3333.sh
Account333333.sh
From this directory, I want to know how I could use grep
to display files based on part of their filename - for example those starting with "Account" or those ending in ".sh".
You can find
find -type f -name "Account*"
Alternative 2 (this might include folder as well)
ls -1 Account*
Alternative 3 (grep, this could include folder as well)
ls -1 | grep -E "^Account"
Use a wildcard (What is this wildcard?):
ls *.sh
The *
will match anything before the ending .sh
that you want. Use the other ls
options for displaying, e.g. -l
to make it a long listing. See man ls
for more info about what you can do with it.
Note that ls
would also list any directory ending with .sh
, not only files.
You can also use find
to overcome this problem.
find . -type f -maxdepth 1 -name "*.sh"
This command only lists "real" files. Using find is something I'd recommend if you want to do something with the found files afterwards. You can do this with the -exec
option.
The standard solution is a pipe:
ls | grep ^Account
With something as simple as "Files starting with Account", globs would also work:
ls Account*
but in general a grep is more powerful, and it doesn't run the risk of overflowing the maximum command line length if your folder is really, really full.
Use the following command
ls *.sh