Bash - move files with similar name from multiple directories to pwd

1

Say I have directories:

mydir1
mydir2
mydir3
mydir4

containing files starting with abcd

I'd like to move all file beginning with abcd to the parent directory. How can I do this?

Here's what I've been playing with:

for file in pwd; mv *abcd ../

atomh33ls

Posted 2014-02-07T13:35:07.473

Reputation: 669

Answers

3

cd to the parent directory, then:

for f in */abcd*;
do mv $f ./
done

that will match mydir1/abcdfoo, mydir2/abcdbar etc. and move them to the pwd (which is the parent directory). If you only want to look in directories called mydir* you could specify

for f in mydir*/abcd*; 
do mv $f ./
done

You could also do

find . -name "abcd*" -type f -exec mv {} ./ \;

that finds all the regular files (not dirs) named abcd* and moves them to the pwd. Find looks recursively from the directory you specify after the find command, that's "." in this case. You can use absolute paths like:

find /path/to/the/parent/dir -name "abcd*" -type f -exec mv {} /path/to/the/destination/dir/ \;

WARNING: I just noticed this when I tried it. If there are multiple files with the same name in different directories e.g. mydir1/abcdfoo, mydir2/abcdfoo and so on, all but one of them will be overwritten, leaving you with just one abcdfoo file in the parent directory.

stib

Posted 2014-02-07T13:35:07.473

Reputation: 3 320

Thanks, I got the following error when using your first suggestion -bash: syntax error near unexpected token 'mv'. The second suggestion worked though... – atomh33ls – 2014-02-07T15:13:17.217

Ah, yes, I tested it in zsh, where the for loops don't need a "do". I'll amend the answer. – stib – 2014-02-07T22:13:59.127