How can I move files by type recursively from a directory and its sub-directories to another directory?

56,015

Solution 1

you can use find with xargs for this

find /thisdir -type f -name "*.ogg" -print0 | xargs -0 -Imysongs mv -i mysongs /somedir

The -I in the above command tells xargs what replacement string you want to use (otherwise it adds the arguments to the end of the command).

OR
In your command just try to move '{}' after mv command.

find /thisdir -type f -name '*.ogg' -exec mv -i {} /somedir \;

Solution 2

In zsh or bash 4, to gather all *.ogg files into /somedir:

mv /thisdir/**/*.ogg /somedir

If you wanted to reproduce the directory hierarchy: (warning, typed directly into the browser)

rsync -a --prune-empty-dirs --include='*/' --include='*.ogg' --exclude='*' /thisdir /somedir

Solution 3

find /thisdir -type f -name "*.ogg" -exec mv {} /somedir \;

You kinda interchanged the arguments for mv

Share:
56,015
Steve Burdine
Author by

Steve Burdine

I have been using Linux for four years now, working on expanding my knowledge about Linux. Into punk rock, riding bikes and still love LP's.

Updated on September 17, 2022

Comments

  • Steve Burdine
    Steve Burdine almost 2 years

    What would be a good way to move a file type from a directory and all of its sub-directories?

    Like "move all *.ogg in /thisdir recursively to /somedir". I tried a couple of things; my best effort was (still not that great):

    find /thisdir -type f -name '*.ogg' -exec mv /somedir {} \;
    

    It returned on each line before each file name,

    mv: cannot overwrite non-directory `/thisdir/*.ogg' with directory `/somedir'
    
  • Hemant
    Hemant almost 14 years
    please don't forget to take backup before trying above commands :-).
  • maxschlepzig
    maxschlepzig almost 14 years
    Btw, for the first -print0 for find and -0 for xargs should be used as possible, to avoid whitespace in filename problems.
  • Hemant
    Hemant almost 14 years
    @maxschlepzig: good point. I will edit.
  • Gilles 'SO- stop being evil'
    Gilles 'SO- stop being evil' almost 14 years
    I strongly suggest using mv -i here, so you don't risk overwriting files if something unexpected happens.
  • Hemant
    Hemant almost 14 years
    @Gilles: thanks :). This is the reason I love stackexchange. Not only we help others but learn also :). one more edit.
  • Noldorin
    Noldorin almost 14 years
    with mv from gnu core utils you can use mv -t <targetdir> and + instead of \;
  • Mark
    Mark over 6 years
    beyond convenient in bash
  • James
    James almost 4 years
    WARNING!!! This does not keep the recursive folder structure at the destination!