Recursively moving files with an extension into a target directory in Bash

Mehran picture Mehran · Jan 15, 2013 · Viewed 31k times · Source

How could I move all .txt files from a folder and all included folders into a target directory .

And preferably rename them to the folder they where included in, although thats not that important. I'm not exactly familiar with bash.

Answer

John Kugelman picture John Kugelman · Jan 15, 2013

To recursively move files, combine find with mv.

find src/dir/ -name '*.txt' -exec mv {} target/dir/ \;

To rename the files when you move them it's trickier. One way is to have a loop that passes each file name through tr / _, which converts slashes into underscores.

find src/dir/ -name '*.txt' | while read file; do
    mv "$file" "target/dir/$(tr / _ <<< "$file")"
done