- How to rename and move files and directories on Linux
- Overview
- Rename files on Linux
- Moving a file on Linux
- Moving and Renaming files on Linux
- Moving Multiple files on Linux
- Moving Directories on Linux
- Verbose Output Flag
- Do Not Overwrite Existing Files
- Do Not Prompt to Confirm Overwrites
- Как переименовать папку Linux
- Как переименовать папку в Linux
- 1. Файловый менеджер
- 2. Команда mv
- 3. Команда rename
- 4. Скрипт Bash
- 5. Команда find
- 6. Утилита gio
- Выводы
- How to Rename Files in Linux
- How to Rename Files in Linux with the mv Command
- Rename File on Linux Using the mv Command
- Rename Multiple Files With the mv Command
- Rename Files on Linux Using the Rename Command
- Remove Rename Command
- Conclusion
- 6 Methods To Rename Multiple Files At Once In Linux
- Introduction
- Rename multiple files at once in Linux
- Method 1 — Using mmv
- Method 2 — Using rename utility
- Method 3 — Using renameutils
- Install renameutils in Linux
- 1. qmv
- 2. qcp
- 3. imv
- 4. icp
- 5. deurlname
- Method 4 — Using vimv
- Method 5 — Using Emacs
- Method 6 — Using Thunar file manager
How to rename and move files and directories on Linux
Overview
In this tutorial, you will learn how to use the mv command to move and renames files and directories on Linux.
Files and directories on Linux as very similar, from a filesystem point of view. This means the operations done on one can be also done on the other, with very few exceptions.
As such, you will notice that commands used to perform actions on files are identical with directories.
Rename files on Linux
To rename a file in Linux you use the mv command. The command accepts two or more arguments. For renaming files, only two arguments are needed, which are the source file and the target file.
The mv command will take the source file specified and rename it to the target file.
To rename a file named student1 to student10, for example, you would run the following command.
Provided the file target is the same directory, all file attributes will remain, including permissions.
Moving a file on Linux
To move a file to another location we use the same method as renaming a file, except the file path should be different.
For example, to move a file from /home/student1/lab-work.log to /var/labs/student1/lab-work.log , you would run the following command.
Moving and Renaming files on Linux
A file can be renamed during a move process using the mv command. You simply give the target path a different name. When mv moves the file, it will be given a new name.
For example, to move a file named student1.txt to /var/students and rename it to class1-student1.txt , you would run the following command.
Moving Multiple files on Linux
The mv command accepts multiple source files, which means we can move two or more files at the same time. When executing the mv command, each file listed will be considered a source with the last path being the exception. The last path will be treated as the target.
For example, to move student1.txt and student2.txt to /var/students , you would run the following command.
Moving Directories on Linux
Moving directories work the same as moving files. We specify the source directory and give a target directory.
For example, to move a directory path /tmp/logs to
/data/logs you would run the following command.
Moving Multiple Directories on Linux
As with files, multiple directories can be moved to a new location. We simply specially all of the directories to be moved, and then give a target directory for them to be moved to.
Verbose Output Flag
The mv command will perform its operations silently. No output will be printed to the screen while files or directories are being moved or renamed.
To instruct the mv command to print out a log of actions being taken, you can use the -v flag. This flag enabled verbosity, which is helpful for auditing.
Do Not Overwrite Existing Files
To force the mv command to not overwrite existing files when moving or renaming a file, use the -n flag.
In the example below, if the student2.txt file already exists, then the mv command will not rename the file and it will exit with an error.
Do Not Prompt to Confirm Overwrites
If you want to forcefully move files or directories and overwrite paths that already exist, you can use the -f flag. This is effective for overwriting old, stale files or directories with new ones with the same name.
Источник
Как переименовать папку Linux
Переименовать папку в Linux не намного сложнее, чем переименовать файл. Вы можете сделать это в графическом интерфейсе или с в терминале с помощью нескольких команд. Как и для других задач в Linux для этой существует множество способов решения.
Можно переименовать не просто одну папку, а выбрать стразу несколько и настроить для них массовое переименование. Вы можете использовать команду mv, rename, а также утилиту find для массового переименования. Но сначала давайте поговорим о том как всё это сделать в файловом менеджере.
Как переименовать папку в Linux
1. Файловый менеджер
Самый простой способ переименовать папку — в файловом менеджере. Например, для Ubuntu это Nautilus. Откройте файловый менеджер и кликните правой кнопкой мыши по нужной папке. В контекстном меню выберите Переименовать:
Затем просто введите новое имя:
После нажатия клавиши Enter папка будет переименована.
2. Команда mv
Команда mv предназначена для перемещения файлов в другое место, однако её можно без проблем использовать чтобы переименовать папку или файл не перемещая его никуда. По сути, если файл или папка перемещается в пределах одного раздела диска, то на самом деле они просто переименовываются, а физически остаются на том же месте. Синтаксис:
$ mv старое_имя новое_имя
Чтобы переименовать папку
/Музыка/Папка 1 в Папка 11 используйте:
Если в имени файлов есть пробелы, то путь к файлу следует взять в кавычки. После выполнения этой команды папка будет переименована:
Обратите внимание, что слеш в конце папки назначения писать нельзя, иначе, ваша папка будет перемещена в указанную папку, если такая существует.
3. Команда rename
Команду rename можно использовать аналогично mv, только она предназначена специально для переименования файлов и папок поэтому у неё есть несколько дополнительных возможностей. Синтаксис команды следующий:
$ rename регулярное_выражение файлы
Но прежде всего программу надо установить:
sudo apt install rename
Самый простой пример, давайте заменим слово «Папка» на «Dir» во всех папках:
Можно пойти ещё дальше и использовать регулярное выражение чтобы заменить большие буквы в названиях на маленькие:
Чтобы не выполнять действия, а только проверить какие папки или файлы собирается переименовывать команда используйте опцию -n:
4. Скрипт Bash
Для массового переименования папок можно использовать скрипт на Bash с циклом for, который будет перебирать все папки в директории и делать с ними то, что нужно. Вот сам скрипт:
#!/bin/bash
for dir in *
do
if [ -d «$dir» ]
then
mv «$
fi
done
Этот скрипт добавляет слово _new для всех папок в рабочей директории, в которой был он был запущен. Не забудьте дать скрипту права на выполнение перед тем, как будете его выполнять:
chmod ugo+x dir_rename.sh
5. Команда find
Массовое переименование папок можно настроить с помощью утилиты find. Она умеет искать файлы и папки, а затем выполнять к найденному указанную команду. Эту особенность программы можно использовать. Давайте для всех папок, в имени которых есть dir добавим слово _1. Рассмотрим пример:
find . -name «Dir*» -type d -exec sh -c ‘mv «<>» «<>_1″‘ \;
Утилита ищет все папки, в имени которых есть слово Dir, затем добавляет с помощью mv к имени нужную нам последовательность символов, в данном случае единицу.
6. Утилита gio
Утилита gio позволяет выполнять те же действия что и с помощью обычных утилит mv или rename, однако вместо привычных путей, можно использовать пути GVFS. Например: smb://server/resource/file.txt. Для переименования папки можно использовать команду gio move или gio rename. Рассмотрим пример с move:
Переименование папки Linux выполняется аналогично тому, как это делается с помощью mv.
Выводы
В этой небольшой статье мы рассмотрели как переименовать папку Linux. Как видите, для этого существует множество способов и всё делается достаточно просто.
Источник
How to Rename Files in Linux
A command-line terminal is an essential tool for administrating Linux servers. It provides Linux users some of the best productivity tools while saving your machine’s resources.
To effectively use the potential of Linux, you will need to have strong knowledge of the fundamentals – simple commands, like renaming existing files and folders. In this tutorial, you’ll learn how to rename folders in Linux.
How to Rename Files in Linux with the mv Command
Shortened from “move,” the mv command is one of the easiest commands to use. It can do two basic but essential tasks when handling files on Linux. One is moving files from one location to another, and the other is renaming one or more files through the terminal.
First, let’s see how renaming files with mv works on Linux.
To begin, we access our server through the command line using SSH. If you are unsure about SSH and would like to learn more, here’s a helpful tutorial.
To access our server, type the following into your terminal:
If we are using a local computer, instead of a server, then we will have to open the terminal from the main menu.
Afterward, it is important to know how the mv command works. To do this, we run the following:
As we can see in the previous image, the basic use of the mv command is as follows:
Here are some of the most popular mv options:
- -f – shows no message before overwriting a file.
- -i – displays warning messages before overwriting a file.
- -u – only move a file if it is new or if it does not exist in the destination.
- -v – show what the command does.
And the parameters are:
[SOURCE] – the source destination of the file
[DESTINATION] – the destination directory.
Rename File on Linux Using the mv Command
If we want to rename a file, we can do it like this:
Assuming we are located in the directory, and there is a file called file1.txt, and we want to change the name to file2.txt. We will need to type the following:
As simple as that. However, if you are not in the directory, you will need to type a bit more. For example:
Rename Multiple Files With the mv Command
The mv command can only rename one file, but it can be used with other commands to rename multiple files.
Let’s take the commands, find, for, or while loops and renaming multiple files.
For example, when trying to change all files in your current directory from .txt extension to .pdf extension, you will use the following command:
This will create a loop (for) looking through the list of files with the extension .txt. It will then replace each .txt extension with .pdf. Finally, it will end the loop (done).
If you want more advanced features, you’ll need to use the rename command, we’re about to cover.
Rename Files on Linux Using the Rename Command
With the rename command, you will have a bit more control. Many Linux configurations include it by default. But, if you don’t have it installed, you can do it in just a minute with a simple command.
In the case of Debian, Ubuntu, Linux Mint, and derivatives:
On the other hand, if you are using CentOS 7 or RHEL:
And, if you are using Arch Linux:
Now, we can start using the rename command. In general, the basic syntax of the rename command looks like this:
It may seem complex at first, but it’s a lot simpler than it might seem.
In this example, we will create a new folder called filetorename, and using the touch command, we will create 5 files.
With the last ls command, you can view the files that you created.
If we want to rename a single file called file1.txt, the sentence would be like this:
If we wanted to change the extension to all files, for example, to .php. We could do it this way:
We can also specify another directory where the files you want to rename are.
We’d like to mention that rename uses a regular expression of Perl, meaning this command has extensive possibilities.
Finally, it is a good idea to check all the command options. You can view them in the terminal by executing:
Some common examples of how to use the rename command are:
-
- Convert filenames to uppercase:
- Convert filenames to lowercase:
- Replace spaces in filenames with underscores:
Remove Rename Command
If you no longer wish to have rename installed on your system, remove it using the software manager. Or from the terminal.
For Debian, Ubuntu, Linux Mint and derivatives:
And for CentOS and RHEL:
That’s it, rename is removed from your Linux machine.
Conclusion
Renaming files in Linux using the terminal is a simple and practical task but sometimes very important. Knowing how to do it is something every server manager should know.
As we have seen, there are two commands that can do it. One is simpler than the other, but both accomplish the task.
We encourage you to continue researching these commands and improving the quality of your everyday workflow.
Edward is an expert communicator with years of experience in IT as a writer, marketer, and Linux enthusiast. IT is a core pillar of his life, personal and professional. Edward’s goal is to encourage millions to achieve an impactful online presence. He also really loves dogs, guitars, and everything related to space.
Источник
6 Methods To Rename Multiple Files At Once In Linux
In this tutorial, we will learn how to rename multiple files at once in Linux using various tools. All examples provided here are tested in Ubuntu 18.04 LTS, however they should work on any Linux operating systems.
Introduction
As you may already know, we use mv command to bulk rename or move files and directories in Linux and Unix-like operating systems.
But, the mv command won’t support renaming multiple files at once. It can rename only one file at a time. What would you do if you wanted to rename multiple files at a time? Worry not!
There are a few other utilities available for batch renaming files in Linux.
Rename multiple files at once in Linux
There could be many commands and utilities to a rename bunch of files. As of writing this, I know the following methods only. I will keep updating the list if I come across any new method in future.
Method 1 — Using mmv
The mmv utility is used to move, copy, append and rename files in bulk using standard wildcards in Linux and Unix-like operating systems. It is available in the default repositories of Debian-based systems.
To install mmv on Debian, Ubuntu, Linux Mint, and Pop OS, run the following command:
Let us say, you have the following files in your current directory.
Now you want to rename all files that starts with letter «a» to «b» . Of course, you can do this manually in few seconds.
But just think if you have hundreds of files and want to rename them? It is quite time consuming process. Here is where mmv command comes in help.
To rename all files starting with letter «a» to «b» , simply run:
Let us check if the files have been renamed or not.
As you can see, all files starts with letter «a» (i.e a1.txt , a2.txt , a3.txt ) are renamed to b1.txt , b2.txt , b3.txt .
Explanation
In the above example, the first parameter ( a* ) is the ‘from’ pattern and the second parameter is ‘to’ pattern ( b#1 ).
As per the above example, mmv will look for any filenames staring with letter ‘a’ and rename the matched files according to second parameter i.e ‘to’ pattern.
We use wildcards, such as ‘*’ , ‘?’ and ‘[]‘ , to match one or more arbitrary characters. Please be mindful that you must escape the wildcard characters, otherwise they will be expanded by the shell and mmv won’t understand them.
The ‘#1′ in the ‘to’ pattern is a wildcard index. It matches the first wildcard found in the ‘from’ pattern. A ‘#2′ in the ‘to’ pattern would match the second wildcard and so on.
In our example, we have only one wildcard (the asterisk), so we write a #1 . And, the hash sign should be escaped as well. Also, you can enclose the patterns with quotes too.
You can even rename all files with a certain extension to a different extension. For example, to rename all .txt files to .doc file format in the current directory, simply run:
Here is an another example. Let us say you have the following files.
You want to replace the the first occurrence of abc with xyz in all files in the current directory. How would you do?
Please note that in the above example, I have enclosed the patterns in single quotes.
Let us check if «abc» is actually replaced with «xyz» or not.
See? The files abcd1.txt, abcd2.txt, and abcd3.txt have been renamed to xyzd1.txt, xyzd2.txt, and xyzd3.txt.
Another notable feature of mmv command is you can just print output instead of renaming the files using -n option like below.
This way you can simply verify what mmv command would actually do before renaming the files.
For more details, refer man pages.
Method 2 — Using rename utility
The rename utility will rename given files by substituting the first occurrence of expression in their name by replacement.
The rename command comes preinstalled in most Unix-like operating systems. If it is not available by default, run the following command to install it on Debian-based systems:
For instance, I have the following files in the current directory.
Let us replace the the first occurrence of abc with xyz wherever found. To do so, run:
Now, verify if the changes have been made with ls command.
Sometimes, you might to just print output instead of renaming the files. If so, use -n flag to display which renames would occur without performing them:
As you can see, the above command didn’t make any changes, instead just displays which renames would occur.
You can force renaming task even if the operation would overwrite existing files using -f flag like below.
If you don’t want to overwrite the files, you can simply convert them to upper or lowercase letters (and vice versa) to prevent «already exists» errors.
To convert all filenames to lower case, so:
Let us check if the changes have been made.
Yes, the letters in the filenames have been changed from lower case to upper case.
Similarly, to convert filenames to lower case, run:
We can remove all blank lines in a filename as well. For example, I have the following file.
To remove all blank spaces in the above filename, run:
Now, the filename doesn’t have any blank spaces.
Replace blank spaces with underscores:
You might want to change the file extension, but not rename the filenames. It is also possible. The following command would rename all *.txt files to *.doc .
Verify the changes using ls command:
To remove extension in all files matching .txt, run:
For more details, refer man pages.
Method 3 — Using renameutils
The renameutils is a set of programs that is designed to batch renaming files and directories faster and easier.
Renameutils consists of the following five programs:
- qmv (quick move),
- qcp (quick copy),
- imv (interactive move),
- icp (interactive copy),
- deurlname (delete URL).
Install renameutils in Linux
Renameutils is available in the default repositories of most Linux distributions. To install it on Arch-based systems, enable the community repository and run:
On Debian-based systems:
Now, let us see some examples.
1. qmv
The qmv program will open the filenames in a directory in your default text editor and allows you to edit them.
I have the following three files in a directory named ‘ostechnix’.
To rename the filenames in the ‘ostechnix’ directory, simply do:
Now, change the filenames as you wish. You will see the live preview as you edit the filenames.
Alternatively, you can cd into the directory and simply run ‘qmv’ .
Once you opened the files, you will see the two columns as shown in the following screenshot.
The left column side displays the source filenames and the right column displays the destination names (the output filenames that you will get after editing).
Now, rename all the output names on the right side as you wish.
After renaming filenames, save and quit the file.
Finally, you will see the following output:
Now, check if the changes have actually been made using ‘ls’ command:
See? All files are renamed. Not just files, the renameutils will also rename the directory names as well.
Here is a quick video demo of qmv program:
If you don’t want to edit the filenames in dual-column format, use the following command to display the destination file column only.
Where, ‘-f’ refers the format and ‘do’ refers destination-only .
Now, you will see only the destination column. That’s the column we make the changes.
Once done, save and close the file.
For more details, refer man pages.
2. qcp
The qcp program works like qmv, but copies files instead of renaming them. In this case, you will get two instances of same file. That means it will keep both original and duplicate files.
Rename the filenames listed on the right side. Save and quit the file. Finally, verify the changes made using ls command:
For more details, refer man pages.
3. imv
The imv program allows us to interactively rename the filenames. Obviously, it is not for bulk renaming. You could only rename the files one by one.
Edit the filename as you like and hit ENTER to rename it.
For more details, refer man pages.
4. icp
The icp program is same as imv , but it copies the files instead of moving them.
For more use cases and commands, please refer man pages.
I don’t know why the developers added these two utilities while we can do the same using mv and cp command.
5. deurlname
The deurlname program removes URL encoded characters (such as %20 representing space) from file names. Some programs, for examples w3m, tend to keep those characters encoded in saved files.
You can this tool for cleaning up the filenames you downloaded from the Internet.
Take a look the the following file.
There are some special characters and numbers in the filename. If you clean it up, just run:
Now, look how the file name is changed.
The filename is clean and readable.
Refer man pages for more details.
Also, refer the project’s website given at the end of this guide.
Method 4 — Using vimv
As the name says, Vimv is a command line utility to bulk rename files using Vim editor. You can, of course, change the editor by changing the value of $EDITOR environment variable.
To install Vimv, git clone the repository:
Copy the vimv binary to your $PATH , for example /usr/local/bin/ .
Finally, make it executable:
Now go to the directory and run the following command to edit the filenames.
You will see the filenames in Vi editor. Press i to switch to interactive mode and edit the filenames as the way you edit text in Vi editor. Once done, press ESC key and type :wq to save and exit.
The files inside the directory should be renamed now. Here is a short video demo.
For more details, refer the project’s GitHub repository given at the end of this guide.
Method 5 — Using Emacs
If you have a system with Emacs editor installed, you can do batch renaming easily by following these steps.
1. Open your Emacs editor.
2. Press Alt+x and type the following and hit ENTER to switch to wdired-mode (short for «writable directory editor mode»).
3. Enter the path to the directory (E.g. /home/sk/ostechnix ) which contains the files to rename and hit ENTER key.
4. Then, press Ctrl+x and Ctrl+q to switch to read-write mode.
5. Now, rename the files. Once done, press Ctrl+c and Ctrl+c (two times) to save the changes. To abort the changes, press Ctrl+c and Ctrl+k .
Watch the demo video:
See? It is very simple to rename multiple files at once.
Method 6 — Using Thunar file manager
The Thunar file manager has built-in bulk rename option by default.
Thunar is available in the default repositories of most Linux distributions.
To install it on Arch-based systems, run:
On Fedora, RHEL, CentOS, AlmaLinux, Rocky Linux:
On Debian, Ubuntu, Linux Mint:
Once installed, you can launch bulk rename utility from menu or from the application launcher. To launch it from Terminal, use the following command:
This is how bulk rename looks like.
Click the plus sign and choose the list of files you want to rename. Bulk rename can rename the name of the files, the suffix of the files or both the name and the suffix of the files.
Thunar currently supports the following Bulk Renamers:
- Insert Date or Time
- Insert or Overwrite
- Numbering
- Remove Characters
- Search & Replace
- Uppercase / Lowercase
When you select one of these criteria from the picklist, you will see a preview of your changes in the New Name column, as shown in the below screenshot.
Once you choose the criteria, click on Rename Files option to rename the files.
You can also open bulk renamer from within Thunar by selecting two or more files. After choosing the files, press F2 or right click and choose Rename .
Suggested read:
And, that’s all for now. Hope this was useful. Do you know any other method to add in this list? Please mention them in the comment section below. I will check and update this guide accordingly.
Источник