Skip to content
Vince Buffalo edited this page May 9, 2022 · 2 revisions

Moving files programatically

I do this in a strange (but I think safe) way: build up the commands you want to use to move the files using find, awk, and sed, then execute them with xargs. Here's an example:

# make some test directories
$ mkdir a_1 a_2 a_3
# find all directories you want to move
$ find . -type d -name "a_*"
./a_2
./a_3
./a_1
# duplicate the filepath name with awk
$ find . -type d -name "a_*" | awk '{print $1 " " $1}'
./a_2 ./a_2
./a_3 ./a_3
./a_1 ./a_1
# modify the second occurrence (this is the /2 at the end) using sed
# to what you want it to be
$ find . -type d -name "a_*" | awk '{print $1 " " $1}' | sed 's/_/_number_/2'
./a_2 ./a_number_2
./a_3 ./a_number_3
./a_1 ./a_number_1
# use xargs -n2 to take TWO at a time (oldname -> new name)
# you must do this otherwise xargs will take multiples!
$ find . -type d -name "a_*" | awk '{print $1 " " $1}' | sed 's/_/_number_/2' | xargs -n2
./a_2 ./a_number_2
./a_3 ./a_number_3
./a_1 ./a_number_1
# now that the above looks like what you should pass to mv, run it:
$ find . -type d -name "a_*" | awk '{print $1 " " $1}' | sed 's/_/_number_/2' | xargs -n2 mv
# it worked
$ ls
a_number_1  a_number_2  a_number_3

For more complicated renaming, you can replace the sed chunk with a more complicated awk or python script.

Clone this wiki locally