How to move files in bulk by skipping multiple files and directories

I am trying to write a shell script that moves all files except those that end with .shand .py. I also do not want to move directories.

This is what I have so far:

cd FILES/user/folder
shopt -s extglob
mv !(*.sh|*.py) MoveFolder/ 2>/dev/null 
shopt -u extglob

This moves all files except those that contain .shor .py, but all directories also move to MoveFolder.

I suppose I can rename folders, but other scripts already have those folders that are assigned to work, so renaming can give me more problems. I could also add folder names, but whenever someone creates a folder, I will need to add its name to the script, otherwise it will also be moved.

How can I improve this script to skip all folders?

+4
source share
2 answers

Use findfor this:

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

What does he do:

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

The flag -execis special: contrary to the previous flags, which were conditions, this is an action. For each match, +that completes the next command, directs findto aggregate the file name at the end of the command at the location marked {}. When all files are found, it findexecutes the resulting command (i.e. mv -t MoveFolder file1 file2 ... fileN).

+5
source

, , , :

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

find -type f maxdepth .

Regexp , Bash script, , , Bash.

+1

Source: https://habr.com/ru/post/1666102/


All Articles