1

How can I move subfolders with a pattern to the new location?

Example list of sources:

  • /data/aaa/_old/
  • /data/bbb/_old/

The destinations should be:

  • /archive/aaa/_old/
  • /archive/bbb/_old/

Is there a way to do this with a regular expression and move?

Something like:

mv /data/(.*)/_old/(.*) /archive/$1/_old/$2
Oliver
  • 121
  • 3

1 Answers1

1

As long, as you not want complex path transformation by regex, jyst use regex on full path for files selection, as in your example. This is a nice idea: https://stackoverflow.com/questions/18640612/archive-old-files-only-and-re-construct-folder-tree-in-archive

Solution combining find and cpio

cd /data

find . -type f -regex "/data/.*/_old/.*" -print0 | cpio -dumpl0 /archive

find . -type f -regex "/data/.*/_old/.*" -print0 | xargs -0 rm

I not tested it, so try it in test environmen.

mmv-ru
  • 682
  • 6
  • 17
  • Thanks, that sounds good with find and cpio. My current command is: `find . -type f -path '*/_old/*' -print0 | cpio -dmpl0 /Volumes/Data/archive/` But there I get some errors `cpio: Can't lstat PATH TO FILE` I think this is where the path or the filename contains special characters as spaces or german umlaut (öäü). Do you have an idea how to prevent this errors? Could I chain the command further with an delete option on successfully copied files? – Oliver Mar 15 '16 at 11:49
  • Im highly ensured, national characters must be not a problem, -print0 and cpio -0 use null terminated string, more like symlink... Or may be your terminal encoding not utf-8 ? It possible by default in cron or some other places. – mmv-ru Mar 18 '16 at 15:54
  • Try verbose mode of cpio -v to report all copied files and look on what it stop. – mmv-ru Mar 20 '16 at 20:11
  • Thank you - The Verbose mode didn't help me… I get the same report `cpio: Can't lstat` even on files without special characters. When I do a `sudo stat FILENAME` I get no errors, I get an expected stat output. I run the find command also with sudo… I'm on an Apple OS X machine perhaps thats the problem? – Oliver Mar 21 '16 at 10:12
  • I have checked the file permissions on the files which cpio can't lstat. I modified them to 755. After that the find and cpio did the job without errors. But why? I had ran the command with sudo? When I ran the command as root with `sudo -i` it worked too. The next is how to delete the **only successfully** copied files? I could do a find and delete but then I can't be sure that all files that find finds are successfully copied. And what is with the directories? – Oliver Mar 22 '16 at 14:31
  • sudo sh -c "find . -type f -path '*/_old/*' -print0 | cpio -dmpl0 /Volumes/Data/archive/" – mmv-ru Mar 24 '16 at 16:20