In this article, we explain how to rename a file, or multiple files in Linux, using two different methods.
Let’s dig into renaming files, the use of mv and rename, and why we use specific tools.
Renaming files with mv – No longer the recommended method
You have a web directory that somehow, the extensions became corrupt. We’re going to use the blog’s files for our example.
ping www.linuxscrew.com #Test connectivity first. wget -m www.linuxscrew.com #Mirror on
We are now the proud owner of a mirrored website. Let’s break it.
That’s a lot of ?amp files we have there, shame we broke them all into .html files. And looks like we have a few extra ones in there to boot. Now let’s move to the pages directory, and fix our mistake of changing everything to a .html file. The internet tells me that doing a simple “mv *[extension1] *[extension2]” should get me what I want.
Would you look at that, an error. How could the mv command not work like expected? Let’s try on the local desktop, Pop_OS. We have two blank .html files. Let’s move them to .pdf.
Same error. Turns out, things change, and the way we used to do things become obsolete. Much like how ifconfig is deprecated, and most of us should move to ip a or ip r. Address and route. Using a specific tool in a non-intended manner can later break procedures. That’s a different soapbox for a different article.
Instead, we should use the specific tool for a specific purpose. In this case, rename over mv. If you want to use mv to rename files, use it sparingly and for single items.
Rename multiple files with rename
We already showed the case of combining two tools to create a robust mass file rename.
find . -depth -type f -name "*?amp" -execdir rename ?amp .html {} \;
Walking through the options.
- The first one, -depth prevents us from breaking child items as it moves through the directory.
- We specified -type f (file) so it won’t break for this use case. But, we want to be robust in our operations. We’ll include depth anyway.
- -name allows us to specify what we’re looking for and forward it to rename with -execdir.
- Then we specify that we’re looking for the pattern ?amp to replace with .HTML.
- Fill the last option with everything pulled from the find command.
Simple! -ish. Let’s pull back, and look at the simple rename function. Here are some logs, let’s rename one.
Renaming single files
For single files it’s “easiest” to use mv, instead of using rename.
There, renamed file. If you want to use rename instead:
rename '' "`date +%Y-%m-%d`"- cloud-init.log
And to save yourself some time, you can store the date as a variable.
date="`date +%Y-%m-%d`"
You’ll notice using rename instead of mv doesn’t cost much extra workload. Simply replace the first expression filter with an empty result.
Appending date to filenames
There. Filenames appended with date. Nice and simple.
Conclusion
Renaming files is a simple task. Learn how to rename directories or check out our other articles for more day to day tasks.