DEV Community

loading...

Rename multiple files with vim and sed

chaitdwivedi
Writing Software for Hardware Engineers!
・2 min read

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:

  1. Using vim (a little long winded - but good to build understanding)
  2. Shell one liner - using sed and xargs

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

\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
Enter fullscreen mode Exit fullscreen mode

Save, quit and execute your file!

chmod 700 exec_me
./exec_me
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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!

Discussion (0)