Linux command line. Move all files and directories in directory, except some files and directories

I have a folder A which has files and directories, I want to move all those files and directories to another folder B, except file, file2, directory, and directory2.

How can this be done?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

With zsh:

setopt extendedglob # best in ~/.zshrc
mv A/^(file|directory)(|2)(D) B/

(the (D) to include dot (hidden) files).

With bash:

shopt -s extglob dotglob failglob
mv A/!(@(file|directory)?(2)) B/

With ksh93

(FIGNORE='@(.|..|@(file|directory)?(2))'; mv A/* B)

Method 2

what i usually do

cd A
ls > a

(assuming you have no ‘a’ file).

vi a

remove whatever file or directory to be kept in place.

mv $(<a) B

Method 3

You can use find with excluded expressions:

find . ! -name . -prune ! -path ./file 
                        ! -path ./file2 
                        ! -path ./directory 
                        ! -path ./directory2 
     -exec mv {} your_destination ;

This solution is inspired by this question.

Method 4

ls | egrep -v '(file|file2|directory|directory2)' | xargs -i mv {} ../B/

Method 5

If ./A and ./B are on the same filesystem and if these files do not already exist in ./B:

file file2 directory directory2

…then this operation should just be atomic:

cd ./A; mv * ../B
for mv in file file2 directory directory2
do mv ../B/"$mv" .
done

If they are not, then there are at least 8 additional cross-device copies done with the above set of commands.

Method 6

$ sudo mv (source folder name) A B(destination foldername)

ex:
create empty dir some sub folder a
1)sudo mkdir -p A/{b/{a,b,c},c,d}

2)ls A/

b c d

3) sudo mkdir B

5)sudo mv a(folder) b(folder)

Method 7

You could use a bash array to store which ones you want to skip and then use the containsElement function demonstrated here:

$ skiplist=(file file2 directory directory2)
$ for f in *; do if containsElement "$f" "${skiplist[@]}"; then continue; fi;
mv -v "$f" B; done


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x