How to move files en-masse while skipping a few files and directories How to move files en-masse while skipping a few files and directories shell shell

How to move files en-masse while skipping a few files and directories


Use find for this:

find -maxdepth 1 \! -type d \! -name "*.py" \! -name "*.sh" -exec mv -t MoveFolder {} +

What it does:

  • find: find things...
  • -maxdepth 1: that are in the current directory...
  • \! -type d: and that are not a directory...
  • \! -name "*.py: and whose name does not end with .py...
  • \! -name "*.sh: and whose name does not end with .sh...
  • -exec mv -t MoveFolder {} +: and move them to directory MoveFolder

The -exec flag is special: contrary to the the prior flags which were conditions, this one is an action. For each match, the + that ends the following command directs find to aggregate the file name at the end of the command, at the place marked with {}. When all the files are found, find executes the resulting command (i.e. mv -t MoveFolder file1 file2 ... fileN).


You'll have to check every element to see if it is a directory or not, as well as its extension:

for f in FILES/user/folder/*do   extension="${f##*.}"   if [ ! -d "$f" ] && [[ ! "$extension" =~ ^(sh|py)$ ]]; then       mv "$f" MoveFolder   fidone

Otherwise, you can also use find -type f and do some stuff with maxdepth and a regexp.

Regexp for the file name based on Check if a string matches a regex in Bash script, extension extracted through the solution to Extract filename and extension in Bash.