There are multiple ways to rename a bunch of files in a programmatic manner in Unix-based systems. Here, I will talk about 2 possible ways:
- Using vim (a little long winded - but good to build understanding)
- Shell one liner - using
Suppose you have a directory with some
.html files that you want to rename to
.htm and add a suffix (
generated) to the base name.
You want to do this:
$ mv file.html file-generated.htm
grep to create a list files to update:
$ ls | grep html > exec_me
$ cat exec_me
The idea is to generate a list of commands that can be executed from the command line to get the desired result.
Perform search and replace in
vim's command mode:
:%s/\(.*\)\.html/mv \1\.html \1-generated.htm/g
\1allows access to data captured in group -
\(.*\). Read about vim modes in vim modes explained
Which should change your file list text to:
mv genindex.html genindex-generated.htm
mv index.html index-generated.htm
mv py-modindex.html py-modindex-generated.htm
mv search.html search-generated.htm
Save, quit and execute your file!
chmod 700 exec_me
This technique is very similar to the vim style, except we don't create a new file - but create and execute commands on-the-fly using
ls | grep html | sed 's/\(.*\)\.html/\1\.html \1-generated\.htm/g' | xargs -L1 mv
Scripting in shell is awesome and powerful, but also dangerous. It is like having a shotgun with no one stopping you from shooting yourself in the foot. Have fun with it but don't go deleting your entire code base!