178
votes

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
3
Instead of a for loop, you should pipe find into while.Dennis Williamson

3 Answers

314
votes

Use find with a wildcard:

find . -name 'mystring*'
31
votes
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'*

8
votes

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 {} \;