I need to move all images with a specific filename string to a specific directory.

This is an example filename


After the 'facility_' there can be 1 to 5 digits.

The following will return a list of the files I wish to move:

ls | egrep "facility_([0-9]*)\+SOURCE[0-9]*"

However I get stuck when trying to move anything this returns. I have tried to use find to move matching files to the moved folder:

for f in 'find ./ | ls | egrep "facility_([0-9]*)\+SOURCE[0-9]*"'; do mv $f moved/; done

But am get a number of errors where mv parses the conditions as a string ...

I had another go with '-exec':

find ./ | ls | egrep "facility_([0-9]*)\+SOURCE[0-9]*" -exec mv moved 

But receive similar errors ...

Advice appreciated. Am I wrong to try this approach at all? Should i just figure out how to do the same regex in 'find'?

1 Answer 1


With find you should not concatenate commands through piping.

It has a nice -regex flag to which you can pass your filename matching string:

find . -regextype egrep -regex ".*facility_([0-9]*)\+SOURCE[0-9]*.*" -exec mv {} DIRECTORY \;

The final \; passes each one of the matching filenames to mv in place of the {}.

As you can see, you need to use .* at the beginning and at the end of the regular expression because find needs to mach on the whole path:

-regex pattern
       File name matches regular expression pattern.  This is a match on the whole path, not a search. For  example, to  match  a  file named './fubar3', you can use the regular expression '.*bar.' or '.*b.*3', but not 'f.*r3'.
  • Thanks for the answer Mr Shunz, when I try that though I get this error find: missing argument to `-exec'
    – Jack
    Oct 15, 2018 at 10:24
  • @Jack sorry, looks like the \+ doesn't work correctly with mv, please use \; instead. I've updated my answer. Oct 15, 2018 at 10:28
  • @MrShunz With GNU mv, you may use -exec mv -t DIRECTORY {} +. Note that when using -exec ... + the {} must come immediately in front of the +. See unix.stackexchange.com/questions/389705
    – Kusalananda
    Oct 15, 2018 at 10:33
  • Thanks, however while find . -regextype egrep -regex "vital_([0-9]*)\+SOURCE[0-9]*" -exec mv {} moved \; doesn't give an error, but unfortunately it doesn't move the file either.
    – Jack
    Oct 15, 2018 at 10:35
  • @Jack does the find without -exec returns any file? Oct 15, 2018 at 11:20

You must log in to answer this question.

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