Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Let's say I have a list of strings. I want to find files with filenames starting with these string.


Strings: filename.could.start.with.this.restoffilename

This list of strings can be an arbitrary number (obviously much more than just two as above).

I want to use a bash script for this and only use what I consider basic linux applications (ls, grep, sed, find etc.), so no python, perl, ruby or other such languages.

share|improve this question
up vote 2 down vote accepted
prefixes=("filename.could.start.with.this" "")

# Turn the prefix array into a find expression (in array form)
for prefix in "${prefixes[@]}"; do
    matchlist+=("-o" "-name" "$prefix*")
matchlist=("${matchlist[@]:1}") # remove the extra "-o" from the beginning

# Search the current directory for plain files with names starting with one of the prefixes
find -x . "(" "${matchlist[@]}" ")" -type f

If your list of filename prefixes wasn't in array form, you'd have to modify this appropriately, e.g.


for prefix in $prefixes; do

Also, this will not behave well if given an empty list of filename prefixes; if that's a possibility, check for this condition first.

share|improve this answer
That's pretty much exactly what I was looking for. However, I'm getting an error on the -x flag on find. I can't see any -x in man find either. – JaHei May 9 '11 at 1:10
@Mikael: that's a flag that (at least on my version) keeps find from crossing volume boundaries. I had a bad experience once (accidentally scanning an entire server volume), so I tend always use it unless I specifically want to search multiple volumes. – Gordon Davisson May 9 '11 at 2:23
Thanks. I'll keep that in mind. I use "find (GNU findutils) 4.4.2" straight from ubuntu repositories. – JaHei May 9 '11 at 12:36
@Mikael: it looks like findutils doesn't implement this (or several other options I'm used to from the BSD version), but you can get the same effect with the -xdev primary (i.e. find . -xdev "(" "${matchlist[@]}" ")" -type f). – Gordon Davisson May 9 '11 at 15:04

BASH FAQ entry #50: "I'm trying to put a command in a variable, but the complex cases always fail!"

Just keep adding find predicates to the array until you have your command.

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .