Linux Move all files to another except some - chaitanyavangalapudi/devops-scripts GitHub Wiki
- Move all files except one
Add below line to your .bashrc or .bash_profile to extend the regex in your commands
shopt -s extglob
If the destination directory to which you need to move your files is present in SOURCE directory, you need to include Directory name also in the REGEX for Negation.
[root@localhost test]# ls
Destdir file1.txt file2.txt file3.txt
[root@localhost test]# mv /home/test/!(file1.txt) /home/test/Destdir
mv: cannot move ‘/home/test/Destdir’ to a subdirectory of itself, ‘/home/test/Destdir/Destdir’
[root@localhost test]# mv /home/test/!(file1.txt|Destdir) /home/test/Destdir
[root@localhost test]# ls
Destdir file1.txt
[root@localhost test]# echo $PWD
/home/test
- Move all files except some
[root@localhost test]# echo $PWD
/home/test
[root@localhost test]# ls
Destdir file1.txt file2.txt file3.txt
[root@localhost test]# ls Destdir/
[root@localhost test]# mv /home/test/!(file1.txt|file2.txt|Destdir) /home/test/Destdir
[root@localhost test]# ls
Destdir file1.txt file2.txt
References:
- https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html
- https://stackoverflow.com/questions/670460/move-all-files-except-one
- https://stackoverflow.com/questions/31596677/why-extglob-except-breaking-except-condition/31597198#31597198
- https://askubuntu.com/questions/986635/how-to-exclude-a-folder-when-using-the-mv-command