1

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

This is an example filename

facility_92+SOURCE1+SOURCE1.0

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

Jack
  • 147
  • 10

1 Answers1

3

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'.
Daniele Santi
  • 4,137
  • 2
  • 30
  • 30
  • Thanks for the answer Mr Shunz, when I try that though I get this error find: missing argument to `-exec' – Jack Oct 15 '18 at 10:24
  • @Jack sorry, looks like the \+ doesn't work correctly with mv, please use \; instead. I've updated my answer. – Daniele Santi Oct 15 '18 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 https://unix.stackexchange.com/questions/389705 – Kusalananda Oct 15 '18 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 '18 at 10:35
  • @Jack does the find without -exec returns any file? – Daniele Santi Oct 15 '18 at 11:20
  • No, but ls | egrep "facility_([0-9]*)\+SOURCE[0-9]*" does. – Jack Oct 15 '18 at 11:56
  • @Jack I just found out that find -regex must match on the whole path. You need a slightly different version of the regular expression. I've updated my answer. – Daniele Santi Oct 15 '18 at 12:16
  • That's great, it works perfectly. Thanks for all your help @MrShunz. – Jack Oct 15 '18 at 13:37