Find all files with a filename beginning with a specified string?

BashFind

Bash Problem Overview


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

Bash Solutions


Solution 1 - Bash

Use find with a wildcard:

find . -name 'mystring*'

Solution 2 - Bash

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'*

Solution 3 - Bash

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRikSaundersonView Question on Stackoverflow
Solution 1 - BashSergio TulentsevView Answer on Stackoverflow
Solution 2 - BashjacanterburyView Answer on Stackoverflow
Solution 3 - Bashmatson kepsonView Answer on Stackoverflow