How to rename file in linux
How to rename file in linux
Как переименовать файл Linux
В этой статье мы рассмотрим как переименовать файл в Linux с помощью терминала, рассмотрим такие возможности, как массовое пакетное переименование файлов, а также регулярные выражения.
Как переименовать файл в Linux с помощью mv
$ mv опции файл-источник файл-приемник
Теперь рассмотрим основные опции утилиты, которые могут вам понадобиться:
Чтобы переименовать файл linux достаточно вызвать утилиту без дополнительных опций. Просто передав ей имя нужного файла и новое имя:
mv file newfile
Как видите, файл был переименован. Вы также можете использовать полный путь к файлу или переместить его в другую папку:
mv /home/sergiy/test/newfile /home/sergiy/test/file1
Переименование файлов Linux с помощью rename
В Linux есть еще одна команда, которая позволяет переименовать файл. Это rename. Она специально разработана для этой задачи, поэтому поддерживает такие вещи, как массовое переименование файлов linux и использование регулярных выражений. Синтаксис утилиты тоже сложнее:
$ rename опции ‘s/ старое_имя / новое_имя ‘ файлы
$ rename опции старое_имя новое_имя файлы
Рассмотрим опции утилиты:
rename ‘s\.htm/\.html/’ *.htm
Или для изображений:
Символ звездочки означает, что переименование файлов linux будет выполнено для всех файлов в папке. В регулярных выражениях могут применяться дополнительные модификаторы:
Можно использовать не только обычную замену, но и полноценные регулярные выражения чтобы выполнить пакетное переименование файлов linux, например, переделаем все имена в нижний регистр:
Переименование файлов в pyRenamer
Если вы не любите использовать терминал, но вам нужно массовое переименование файлов Linux, то вам понравится утилита pyrenamer. Это графическая программа и все действия здесь выполняются в несколько щелчков мыши. Вы можете установить ее из официальных репозиториев:
sudo apt install pyrenamer
В окне программы вы можете видеть дерево файловой системы, центральную часть окна, где отображаются файлы, которые будут изменены, а также панель для указания параметров переименования.
Вы можете удалять или добавлять символы, переводить регистр, автоматически удалять пробелы и подчеркивания. У программы есть подсказки, чтобы сделать ее еще проще:
Опытным пользователям понравится возможность pyRenamer для переименования мультимедийных файлов из их метаданных. Кроме того, вы можете переименовать один файл если это нужно. Эта утилита полностью реализует функциональность mv и remove в графическом интерфейсе.
Выводы
В этой статье мы рассмотрели как переименовать файл в консоли linux. Конечно, есть и другие способы, например, написать скрипт, или использовать файловые менеджеры. А как вы выполняете сложные операции по переименованию? Напишите в комментариях!
How to Rename Files in Linux
Renaming files in Linux is one of the easiest tasks that you can accomplish straight from the command line.
There are quite a few ways you can achieve this and in this guide, I will take you through how you can rename files in Linux.
1) Rename files using mv Command
The mv command is one of the easiest commands you can use to rename files in Linux. The syntax is quite straightforward.
Syntax
Example
I have created a new folder in my home directory called files. In the folder, I have a document called file1.txt.
To rename the ‘file1.txt’ to ‘file2.txt’, the command will be
You can verify the results using the ls command
Output
If the file is located in a file path e.g. / home/winnie/file1.txt, the syntax will be
NOTE:
If you specify a different file path, the mv command will simply move it to a different location without renaming it.
2) Rename multiple files using the rename command
The rename command can also be used to rename multiple files from one format to another. The syntax is
For example, I have 5 files- file1.txt, file2.txt, file3.txt, file4.txt, and file5.txt
To rename them all files (*.txt) to pdf (*.pdf) run
The wildcard symbol means that all files will be affected.
To change filenames from lowercase to uppercase run
In the above case, all lowercase png files will be converted to Uppercase
To view the man page of rename run
3) Using Metamorphose2 GUI tool
For GUI lovers, Metamorphose is a handy and powerful tool for renaming operations. Metamorphose is a free and open source cross-platform file and folder renamer, available for both Linux and Windows.
First off, head out to Metamorphose website and select your distribution’s installer. A couple of installer options are available e.g. Debian files for Ubuntu and Debian and RPM for RedHat based distros such as CentOS.
Once downloaded use the dpkg command to install
After successful installation of Metamorphose2, launch it on a terminal, by running
Choose your preferred language and click ‘Ok’ button
Click on the renamer tab. A Window like the one below will be displayed. On the left pane is a list of actions that you can take when renaming. in the middle section, these actions are further explained in detail.
Next, click on ‘Picker‘ tab and click on the folder containing the files you want to rename. Highlight the files.
Thereafter, click on the ‘Renamer‘ tab again and this time define the renaming rules. In the example below, I’m replacing ‘file’ with ‘doc’.
The bottom section gives you a preview of how your files will be renamed.
Once satisfied, click on the ‘Go‘ button
3) Using Pyrenamer GUI tool
Pyrenamer is yet another handy tool you can use to rename a batch of files simultaneously in Linux. To install in Ubuntu run
To launch Pyrenamer run
Once launched, scroll down to your directory and select the files you want to rename. Next, choose the actions you wish to apply. In my case, I will replace the extension txt with pdf.
To effect the changes, I will finally click on ‘Rename‘
Conclusion
In this tutorial, we have touched on various ways you can rename files (both individual files and batches of files) on the terminal and using GUI tools. Found nomino a batch rename utility for developers.
Give it a try and let us know how it went! Thanks and keep it locked for more informative tutorials!
How to Rename Files in Linux
Read more tutorials by Michael Franklin!
Table of Contents
Are you new to the Linux operating system? If so, common tasks such as renaming files and folders may be different than what you are used to. But don’t fret. The concept of renaming files in Linux is similar to how it’s done in other operating systems.
In this tutorial, you’ll learn many ways to rename single and multiple files in Linux, both via GUI and running commands in a terminal.
Let’s get started!
Table of Contents
Prerequisites
To follow along within this tutorial, make sure you have the following:
Rename Files in Linux with File Manager
If you are used to managing files via GUI, let’s start this tutorial to rename files with a file manager. GUI file managers are neat since you can see the files in plain sight. One of those file managers available in Linux is GNOME’s former file manager, Nautilus. This tutorial demonstrates renaming files using the Nautilus file manager.
Linux’s other file managers are Konqueror, Dolphin, Krusader, Thunar, Nemo file manager, and Sunflower file manager. These file managers perform the same task but renaming files or directories may be slightly different.
Launch your terminal, then run the command below to install Nautilus ( install nautilus ) with the apt package manager if you don’t have it yet on your machine. The sudo command elevates the command with sudo/administrator rights.
Renaming a Single File
Renaming a single file in Nautilus takes only a few clicks, like in Windows File Explorer.
To rename a single file, open Nautilus, right-click on the file you want to rename, and choose Rename, as shown below.
This example focuses on renaming files, but the process is the same to rename both files and directories.
Now type the new file name to replace the original file name, press Enter or click on Rename, and that’s it.
Renaming Multiple Files using Nautilus File Manager
Like Windows, Ubuntu gives you more options on how you want to rename multiple files at once.
To rename multiple files, select all files you want to rename, right-click on any of them and choose Rename. A pop-up window will appear where you can choose how you want to rename the files you selected.
Below, there are two options to choose from depending on how you want to rename the selected files.
Renaming Files using a Template
To rename files using a template, select the Rename using a template option.
Now enter the replacement name in the empty field to rename files with a template, and click on the +Add button and choose from the templates. For this tutorial, select the first one (1,2,3,4) and click Rename. This option adds incrementing numbers to each file after the replacement filename (Text1, Text2,…).
Notice the file names changed to Text, followed by incrementing numbers.
Finding and Replacing Words in the File Names
To rename multiple files with a specific file name, select the Find and replace text option.
Enter the text in the Existing Text field and the replacement text in the Replace With field, then click Rename to replace the text. This option finds and replaces certain texts in file names.
Now, you can see below that you’ve replaced the word “Text” with “File” in each file name.
Renaming Files with the mv Command
If running commands is your thing instead of navigating in a GUI, prepare yourself to learn how to rename files in a terminal. Renaming files in the Linux terminal is similar to doing it in other command-line environments, such as PowerShell. You run the commands to rename the original file name with the target file name, and that’s it.
There are two scenarios in renaming a file. The first is renaming a file from the working directory, and the second is by specifying the full path. Take a look at the mv command syntax below to rename a file, where the source is the original name, and the destination is the replacement name.
Renaming a Single File with the mv Command
While the mv command syntax is still fresh in your mind, let’s try renaming a single file.
To demonstrate how to rename a single file and directory:
1. Launch your terminal, then run the series of commands below to create a directory and two text files.
2. Next, run the ls command to list the files inside the working directory. Below, you can see that file1.txt and file2.txt exist in the
Renaming a directory is the same as renaming a file, like this: mv
symbol denotes the home directory.
4. Finally, rerun the ls command to list the files in the working directory.
Below, you can see that file1.txt is now renamed as file10.txt.
Renaming Multiple Files with a For Loop
If you’re too busy with other tasks at hand and want to rename all files in one go, you’ll need to use a for loop statement like the one below.
Copy the code below as-is, paste it in your terminal, and press Enter. The code below scans each text file in the working directory and renames the files with “File” followed by an incrementing number.
Pasting the code into your terminal works fine, but as good practice, it’s better if you create a script file to run instead.
Below, you can see in action how the code renames all files.
Renaming Files in Linux with the rename Utility
If you’re renaming a single file in your daily routine, then the mv command will suffice. But perhaps you’re aiming to rename multiple files with the same pattern at once? For example, renaming files that start with a certain word (file). In that case, install the rename utility instead.
The rename utility renames multiple files, changes file name formats, and overwrites files.
To install the rename utility, run any of the commands below depending on the Linux distro you’re working on.
You can see below the rename command syntax.
Renaming Multiple Files
With the rename command syntax in mind, you can now rename files that have the same pattern. What’s great about the rename command is that you don’t need to declare a loop function to rename multiple files as you did in the “Renaming Multiple Files with a For Loop” section.
Perhaps you want to rename files with certain words on them. If so, take a look at the Perl regular expression ( ‘s/file/myfile/’ ) in the sample command below. Perl regular expressions define a string pattern based on the Perl programming language.
Now run either of the rename commands below to replace the word file with myfile in each text file’s name inside the working directory or the
Below, you can see that each “file” word in the text files is renamed to “myfile.”
Changing File Extensions
Other than file names, the rename command also renames file extensions. Perhaps you’ve created files with the wrong file extension. In that case, you’ll specify the file extension to change in a Perl expression when you run the rename command.
As you see in the image below, the .txt extensions changed to .html
Changing File Names to Uppercase and Lowercase
Instead of incorrect file extensions, you may be dealing with filenames in lowercase and vice versa. Perhaps you’re trying to find a file specifically in uppercase, not knowing the file name is in lowercase.
Linux is case-sensitive, so let’s ensure you have each file name’s letter case right. Letter case is basically the distinction of texts between lowercase and upper case.
Run either of the rename commands below to change all lowercase ( a-z ) file names in the working directory ( * ) to uppercase ( A-Z ) and vice versa.
You can see below both results of changing a file name letter case.
Replacing and Removing Spaces in File Names
Like a file name’s letter case, you may have trouble finding files if they have spaces in their file names. Let’s fix that by either replacing spaces with a character or removing the spaces altogether.
Run the rename command below to replace spaces in all file names with an underscore ( _ ) in the working directory. Since underscore is a metacharacter, escape it with a backslash ( \\_ ) to declare the underscore literally. Metacharacters are special characters with special meanings in a computer program.
Notice the g in the Perl expression tells the command to replace all matches (spaces), and not just the first one.
Below, you can see that the command replaced all spaces with underscores.
To remove all spaces in a file name instead of filling them up with a character, run the command below.
In the Perl expression below, the asterisk after the blank space ( / * ) matches all occurrences of spaces in a file name and not just the first one. The replacement character is empty ( // ), so the rename command removes all ( g ) spaces.
Now you can see below that all spaces are removed from each file name.
Capitalizing the First Letter of Each Word in a File Name
If you prefer to keep the spaces and capitalize the first letter of each word in a file name instead, you’ll need a more complex Perl expression. Take a look at the sample command below.
Below, you can see that each word in the file names starts with a capital letter while leaving the file extensions untouched.
Conclusion
Throughout this tutorial, you’ve learned many ways to rename Linux files via GUI and command-line terminal. You now have a solid understanding of how to manipulate names for single and multiple files at once.
Why not learn Linux shell scripting, and create a script to automate renaming files in Linux?
Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.
More from ATA Learning & Partners
Recommended Resources!
Recommended Resources for Training, Information Security, Automation, and more!
Get Paid to Write!
ATA Learning is always seeking instructors of all experience levels. Regardless if you’re a junior admin or system architect, you have something to share. Why not write on a platform with an existing audience and share your knowledge with the world?
ATA Learning Guidebooks
ATA Learning is known for its high-quality written tutorials in the form of blog posts. Support ATA Learning with ATA Guidebook PDF eBooks available offline and with no ads!
How Do I Rename a File in the Ubuntu Terminal?
However, to use effectively this CLI application, you should have strong knowledge about basic Linux commands and fundamentals such as create, delete and renaming an existing file. Different commands are available in the Ubuntu Linux system to rename a file that we will explore in this article.
We will provide comprehensive details in this tutorial on how you can rename a file in Ubuntu using the command-line application Terminal. All commands have implemented for the demonstration on the Ubuntu 20.04 Linux system.
Renaming Files in Ubuntu 20.04 LTS System Using Terminal
The two different commands ‘mv’ and ‘rename’ are available in the Ubuntu Linux system to rename a file via terminal or command-line approach. Let us discuss each command in detail.
Rename File in Ubuntu Using the mv Command
Before using the ‘mv’ command, you should know how it works on your system. The basic syntax of the ‘mv’ command is given below:
The most popular ‘mv’ command options are provided below:
-f – Displays no message or alerts before overwriting a file name.
-i – Displays prompt confirmation or warning messages before renaming a file.
-u – It moves a file if the file does not exist on the specified destination or in case of a new file.
The file source can be the destination of one or more files. The destination only represents a single file.
Example
For example, to rename the file ‘testfile1.txt’ to ‘testfile2.txt, you need to run the following command:
How to Use the mv Command to Rename Multiple Files?
Usually, you can only rename a single file using the move command. To rename multiple files using the mv command, you can use the mv command to combine with different commands. Let us say, mv command can be used along with for loop, while loop, and find command.
How to Use the Rename Command to Rename Files in Ubuntu?
Using the rename command, you can rename multiple files of a current directly at once. This command contains more advance features as compared to the ‘mv’ command. For renaming files using the rename command, you should have basic knowledge about regular expressions usage.
In most Linux distributions, the ‘rename’ command is installed by default. However, if you have not installed the rename command on your Ubuntu system then, it can be easily installed on Ubuntu and its derivatives by running the following command:
Syntax of Rename Command
Using the following syntax, you can use the rename command:
The rename command will rename files according to the specific regular Perl expressions.
Example
When you use the rename command followed by option ‘-n’, it also displays the file names to be renamed and renaming them as follows:
The above command displays the following result on the terminal window:
To change or rename the file name using rename command use the following command:
Example
For example, we want to rename a single file with the name ‘testfile.txt’ to newtestfile.txt. In this case, the above command will be modified into the following form:
To see more usage of rename command, let us try the following examples:
For example, to rename all those files, which contain spaces in file name and you want to replace it with underscores. In this case, the rename command will help you in the following way:
Using rename command, you can convert the file name in all lowercase letters as follows:
Similarly, to convert the file name to all uppercase letters, use the following command:
To explore more options and uses of rename command, type the following terminal command:
Conclusion
We discussed in this article how to rename files in Ubuntu 20.04 LTS distribution using the terminal application. Moreover, we explored the working and uses of the ‘mv’ and ‘rename’ commands for renaming a file. From the above discussion, we concluded mv command is useful for renaming a file but, rename command offers more advanced options for file renaming in the Ubuntu system.
About the author
Samreena Aslam
Samreena Aslam holds a master’s degree in Software Engineering. Currently, she’s working as a Freelancer & Technical writer. She’s a Linux enthusiast and has written various articles on Computer programming, different Linux flavors including Ubuntu, Debian, CentOS, and Mint.
How to Rename a File in Linux With Simple Command Line Options
Developed in the early 1990s, Linux has remained a popular operating system for both personal use and commercial servers. Today, there are over 600 Linux distributions (versions) available, though only a handful of them remain in common use. Based on Unix, the Linux system is prized for its portability, reliability, and stability. There are many individuals (primarily industry professionals) who prefer using Linux over any other operating system.
That said, Linux does require some advanced knowledge to use. While today most Linux distributions have a GUI (graphical user interface), many don’t. Working with Linux requires prior knowledge because most commands are given through a command-line text.
If you’ve worked in DOS or have programmed in C, you will know how to use a command line. But with Linux, it’s all about knowing individual commands — including the commands to rename and move files.
Today, we’re going to take a look at how to rename a file in Linux. We’ll look at the rename tools that Linux offers, renaming a single file, how to rename files and directories, and renaming multiple files through batch rename.
Last Updated July 2022
Linux Administration (Ubuntu and CentOS) for Beginners. Get the Linux skills to boost your career and get ahead. | By Andrei Dumitrescu, Crystal Mind Academy
How to rename a single file in Linux
If we need to rename a single file in Linux, we have two options: we can create a copy of the file with a new name (and delete the old one) or we can rename the file by moving it (with the MV command).
Renaming a file by copying and deleting it
Linux users copy a file by using the “cp” command. When you copy a file, you give the source files and rename the files.
As an example, if we were to rename “august.png” to “september.png”:
This will create a copy of the file with a new name. But now you’ll have two copies. You’ll resolve this by deleting the old file. You delete with “rm.”
You may be wondering why this is so cumbersome compared to Windows, where you’d just rename a file. Linux has a lot of power, but it manages that power by putting it in the user’s hands. Linux users will perform more operations incrementally, but they have complete control over how those operations are performed.
This gives way to another issue: We could have named that second file september.jpg or september.doc. And then the file would no longer work! Linux provides a lot of power and a lot of freedom.
Renaming a file by moving it
You may be relieved to know that there is an easier method. But it’s a counterintuitive one. You can rename a file by “moving it” to a new file name.
This actually does what you would think of as a “rename” command and in a single step. But it should be noted that it’s also the general “move” command. So, you are moving the file at the same time. If you move it to a different directory, it will be moved as well as renamed.
As with the cp command, you have to be aware of file extensions. For example, say we introduced a typo and typed:
That action would break our file.
File extensions and renaming
For the most part, Windows protects you from changing the extension of a file. When you click a file in Windows to rename it, it only highlights the actual name, not the extension. You need to do a little work to change the extension of a file.
If a file is no longer working after you’ve moved, renamed, or copied it, it’s very likely that it’s because of an error with the file extension.
How to rename multiple files in Linux
What if you wanted to rename multiple files in Linux? This is where we start to see the advantages of using a command-line system.
Let’s say we did make a mistake. We changed everything to JPGs, but instead, they need to be PNGs. We can do this like so:
What this does is it uses a wildcard operator (*) to select any file that ends with JPG and changes that to a PNG. We had better know what we’re doing, though, because if there were any actual JPGs, they’re broken now.
Wildcards are one of the simplest forms of regular expressions. If we had wanted to rename the files in Windows, we would have had to click on them one by one. To rename the files in Linux, we can just use an expression to highlight them all. For that reason, power users in Linux can perform operations very quickly.
Renaming a directory in Linux
One of the quirks of Linux and Unix is that not much changes whether you’re using files or directories. A directory is more or less a blank file that contains other files. If we had a directory called “2021” and we wanted to rename it to “2022,” we would do this:
It’s as simple as that. Existing directories are treated like existing files that do not have a file extension by the MV command.
Rename a file while moving it in Linux
Earlier, we noted that we are using the MV command to rename files and that we could also move the file to a different directory if we so chose.
Now let’s say we want to rename august.png to september.png and also move it into the 2022 directory.
As again, both the directory and the file name (and its extension) are just pointers to where data is. This remains consistent throughout Linux.
Using flags (options) for your operations
Linux makes it possible to use something called “flags,” or options, with its commands. This controls how the command is performed.
Both of these option flags can be helpful when using the MV command in Linux.
Using the interactive renaming function in Linux
We’ve noted a couple of times that it’s possible to make large, potentially irrevocable mistakes in Linux. But there’s also a way to get around this. If you add the “-i” option with the MV command, you’ll be prompted before anything is done.
Let’s say we type:
But the problem is, we’ve already created september.png. It already exists! The “interactive” function will let us know we’re about to overwrite an existing file. We can then type “Y” or “N” to either confirm the action or deny it.
If we knew that it was going to be overwritten anyway, we may be fine with it. But otherwise, we might want to know that there’s another file in danger.
Using the verbose option to track what’s happening
This will tell you exactly what it has done to the source files and the new files. And you can also:
Mass moving and renaming files in Linux
Sometimes you need to move and rename a large number of files in Linux. Consider that you might have an entire directory of files that have to be either changed or moved. This could happen if you installed something into the wrong directory.
For this, Linux has another command altogether: MMV. MMV can be used to move, link, and append files. It’s a non-destructive method of doing so; it will try to identify any potential errors or collisions.
This is particularly valuable because you don’t want to accidentally ruin a lot of files at once.
The above would be another way of changing all PNGs to JPGs, in the event that for instance, a large number of files had the wrong extension. This could happen if you had copied the original file over incorrectly.
But you’ll notice that we could have done this with the MV command, too. The only difference is that MMV is a more careful way of doing this.
If you wanted to mass copy a lot of files, you could even copy over the entire directory:
And that would copy 2021 to 2022 while still leaving 2021. Copying is less dangerous than moving because copying doesn’t inherently delete the original files. Moving does. This is one reason why when renaming a file, we looked at the CP function before the MV function — there is less that can go wrong with the operation because it’s not inherently destructive.
Installing rename in Linux
At this point, you might be thinking “Why can’t I just rename?” Actually, you can. There is a “rename” command in Linux, but you would need to install it.
On your administrative account for Ubuntu or Debian:
For Fedora or CentOS:
(If you have a different distribution, look up your installation syntax.)
This will install the “rename” package. After you install rename, you’ll be able to use complex regular expressions to rename your files.
Complex regular expressions are a topic in and of themselves. We saw that * can be used as a wildcard. But with regular expressions, we can also select things like “any file that starts with letters but ends with numbers” or “any file that has 59 in it.” Regular expressions can be used to identify email addresses or other patterns — they are very powerful but take some practice.
The rename command will not operate much differently from MV, MVV, or even CP. The difference is that you’ll have a dedicated function called “rename” that you can use. There are many function packages for different Linux distributions that you can install. If you’re trying to complete an operation and you can’t find it in vanilla Linux, consider looking for a package.
Getting started with Linux
Linux has an internal manual ($ man) that can be used to look up commands. To look up more information about the move command in Linux, you can also always type in:
Linux requires a lot of memorization. For the most part, you just need to know what’s possible in the system. Once you know what’s possible, you should be able to reference the manual to figure out how.
But you should always remember that Linux does what it’s told — there are fewer safeguards with the Linux system. While Windows might alert you that you’re overwriting a file, Linux isn’t likely to alert you unless you specifically ask that it does. If you’re just learning Linux now, a great way to do so is through a Linux bootcamp or workshop. There are so many distributions of Linux, you’ll also want to decide which distribution you want to use first. Check out our guide to finding the best Linux distro!
Page Last Updated: September 2021