192

I have a directory with roughly 100000 files in it, and I want to perform some function on all files beginning with a specified string, which may match tens of thousands of files.

I have tried

ls mystring*

but this returns with the bash error 'Too many arguments'. My next plan was to use

find ./mystring* -type f

but this has the same issue.

The code needs to look something like

for FILE in `find ./mystring* -type f`
do
    #Some function on the file
done
SecretAgentMan
  • 2,756
  • 6
  • 18
  • 38
RikSaunderson
  • 3,165
  • 6
  • 30
  • 49

3 Answers3

342

Use find with a wildcard:

find . -name 'mystring*'
2240
  • 1,570
  • 2
  • 7
  • 23
Sergio Tulentsev
  • 219,187
  • 42
  • 361
  • 354
33
ls | grep "^abc"  

will give you all files beginning (which is what the OP specifically required) with the substringabc.
It operates only on the current directory whereas find operates recursively into sub folders.

To use find for only files starting with your string try

find . -name 'abc'*

jacanterbury
  • 1,305
  • 1
  • 23
  • 32
  • Don't use ls | grep. Use a glob or a for loop with a condition to allow non-alphanumeric filenames, see https://github.com/koalaman/shellcheck/wiki/SC2010 – Nicolas Massart Oct 26 '21 at 13:20
8

If you want to restrict your search only to files you should consider to use -type f in your search

try to use also -iname for case-insensitive search

Example:

find /path -iname 'yourstring*' -type f

You could also perform some operations on results without pipe sign or xargs

Example:

Search for files and show their size in MB

find /path -iname 'yourstring*' -type f -exec du -sm {} \;
matson kepson
  • 1,812
  • 15
  • 17