Rename a File in Linux – Bash Terminal Command mv part 1 (ok)
https://www.freecodecamp.org/news/rename-file-linux-bash-command/
Last updated
https://www.freecodecamp.org/news/rename-file-linux-bash-command/
Last updated
Renaming files is a very common operation whether you are using the command line or the GUI.
Compared to the GUI (or Graphical User Interface), the CLI is especially powerful. This is in part because you can rename files in bulk or even schedule the scripts to rename files at a certain point in time.
In this tutorial, you will see how you can rename files in the Linux command line using the built-in mv
command.
mv
CommandYou can use the built-in Linux command mv
to rename files.
The mv
command follows this syntax:
Here are some of the options that can come in handy with the mv
command:
-v
, --verbose
: Explains what is being done.
-i
, --interactive
: Prompts before renaming the file.
Let's say you want to rename index.html
to web_page.html
. You use the mv
command as follows:
Let's list the files and see if the file has been renamed:
mv
Let's discuss a script where you can rename files in a bulk using a loop and the mv
command.
Here we have a list of files with the extension .js
.
Next, you want to convert them to .html
.
You can use the command below to rename all the files in the folder:
Let's break down this long string to see what's happening under the hood:
The first part [for f in *.js
] tells the for
loop to process each “.js” file in the directory.
The next part [do mv -- "$f" "${f%.js}.html
] specifies what the processing will do. It is using mv
to rename each file. The new file is going to be named with the original file’s name excluding the .js
part. A new extension of .html
will be appended instead.
The last part [done
] simply ends the loop once all the files have been processed.
As you can see, renaming files is quite easy using the CLI. It can be really powerful when deployed in a script.
What’s your favorite thing you learned here? Let me know on Twitter!
You can read my other posts here.
Image by storyset on Freepik
ADVERTISEMENTADVERTISEMENTADVERTISEMENT
I am a DevOps Consultant and writer at FreeCodeCamp. I aim to provide easy and to-the-point content for Techies!
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started