-2

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.

  • 3
    Almost a duplicate of https://unix.stackexchange.com/a/203046/100397 – Chris Davies Nov 13 '20 at 23:02
  • 1
    Well, I went on a quest - to find out why the 'no no no'. And, I learned you shouldn't process the output of 'ls' for a couple of reasons. Thanks to @roaima, I learned something new! Now, to be honest (for my simple needs), I'd probably still us 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:05
  • 1
    @KGIII great to hear you've expanded your skillset; I love doing that too. It's more than this, though; for names you can just use wildcards, so ls -d *a* to match file names containing a (use man ls to find out about -d) – Chris Davies Nov 16 '20 at 09:32

1 Answers1

1

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 of a, 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*
Chris Davies
  • 116,213
  • 16
  • 160
  • 287