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
sed
andxargs
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
Using vim
Create a list of files
Use ls
and grep
to create a list files to update:
$ ls | grep html > exec_me
$ cat exec_me
genindex.html
index.html
py-modindex.html
search.html
Search and replace to generate commands to execute
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
\1
allows 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
./exec_me
Using sed and xargs
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 xargs
ls | grep html | sed 's/\(.*\)\.html/\1\.html \1-generated\.htm/g' | xargs -L1 mv
Conclusion
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!
Top comments (0)