Aug 16 2007
∞
MV files fast: bulk rename several files at once on linux.
I’m still not super-familar with bash, but I love working in it — everything is faster. Take this handy dandy little line, which you can use to rename multiple files easily:
for f in *;do mv $f ${f/test/prod};done
I probably don’t need to tell those of you developing modules (where your primary files share the same prefix) how much of a time saver this is. For example, if you want to build your functionality using the imaginary example_mod module as a base, you could do this:
cp -rp example_mod my_mod
cd my_mod #otherwise you're gonna replace *BOTH* instances
for f in example_mod.*; do mv $f ${f/example_mod/my_mod};done
You still need to edit the info and module files so they don’t contain previously defined functions, but I suspect a little fancy sed work and you’d be all set.
from Shell Geek
EDIT:
I’ve noticed a lot of people come here to try and figure out how bulk renaming works, so I feel like I should add some clarity. Let’s look at the command:
for f in *;do mv $f ${f/test/prod};done
Here’s what’s happening:
for f in *;
that’s a single command — if you didn’t notice — the semicolon indicates that the command ends after the asterix. We’re essentially saying “I’m starting a ‘for’ loop, wherein $f will stand for each file in my current directory”.
The next command is
do mv $f ${f/test/prod};
The ‘do’ here is a part of the ‘for’ loop, it tells bash what we want to do for each file ($f) in the directory. In this case, we want to replace all instances of ‘test’ with ‘prod’. Let’s say I have 3 files. One is named ‘test.txt’, one is named ‘test.sh’, and one is named ‘thegreatest.as’. We are essentially running the following commands:
mv test.txt prod.txt mv test.sh prod.sh mv thegreatest.as thegreaprod.asThat is to say, the $f references our filename, whereas ${f/test/prod} says ‘replace any instances of “test” with “prod” in all of our filenames. This is where the syntax is a little weird, right? I don’t know enough about how {} function in bash to be entirely clear, but essentially, we say “take my variable $f. Replace whatever I say after this / with the next bit of text i have after the second /”. The format of var/find/replace should be very familiar to you if you use vim or anything that uses regexes, so I think both of us can just take the brackets as a magic eval for now. If you’ve got a nice story to tell about what brackets actually mean to bash, please let me know. Anyhow, after that line, we say
donewhich closes the ‘for’ loop we opened with for f in *;. Hope this makes sense and helped you out. Leave a comment if it doesn’t or if I’ve left something out, and I’ll add more detail.