I want to list all the files, in directory I am currently in, with for example "a" in their name. I know that the first part of the command would be ls -l
, but i do not know how to finish it.
1 Answers
You should read up on glob wildcards, including *
and ?
.
*
matches zero or more characters?
matches exactly one character[...]
matches one of a set of characters (eg[abc]
matches any ofa
,b
,c
)
So to find all file names containing abc
you simply use the glob *abc*
. This can be used anywhere you want this list:
ls *abc*
rm -i *abc*
echo *abc*
A note of warning, though, to say that the command line gets run after the expansion. (It's the shell performing the expansion, not the command.) So if you had a filename like -abc
, the expansion of ls *abc
will result in ls -abc
, which will result in ls
parsing the set of flags -labc
with no filename argument. Fix this by prefixing wildcard expansions with ./
to force an explicit path to the current directory
ls ./*abc*
rm -i ./*abc*
echo ./*abc*
Note that for ls
, if any of the arguments is a directory, the contents of that directory will be listed instead of the directory name itself. Fix that with the -d
flag, and while you're there use -q
if your version of ls
supports it,
ls -dq ./*abc*

- 116,213
- 16
- 160
- 287
ls | grep a
but that's 'cause I'm inherently lazy. Definitely don't do that. If you want to learn why you shouldn't parse 'ls' then click here. And now I know! – KGIII Nov 16 '20 at 03:05ls -d *a*
to match file names containinga
(useman ls
to find out about-d
) – Chris Davies Nov 16 '20 at 09:32