- Linux Rename File Command
- How to rename a file Linux?
- Examples: Renaming files with mv Command
- Linux rename a file syntax
- How to use rename command to renames multiple files
- Detailed information about mv command
- Как переименовать файл Linux
- Как переименовать файл в Linux с помощью mv
- Переименование файлов Linux с помощью rename
- Переименование файлов в pyRenamer
- Выводы
- Rename files with mv Command
- Rename multiple files with mv command
- Rename files with rename Command
- Conclusion
Linux Rename File Command
How to rename a file Linux?
The syntax is as follows:
mv old-file-name new-file-name
mv [options] old-file-name new-file-name
mv file1 file2
Examples: Renaming files with mv Command
In this example, rename a file called resumezzz.pdf to resume.pdf. Open a command-line terminal (select Applications > Accessories > Terminal), and then type:
mv resumezzz.pdf resume.pdf
If resumezzz.pdf is located in /home/vivek/docs/files directory, type:
cd /home/vivek/docs/files
mv resumezzz.pdf resume.pdf
OR
mv /home/vivek/docs/files/resumezzz.pdf /home/vivek/docs/files/resume.pdf
Use the ls command to view files:
ls -l file1
ls -l file1 file2
ls -l /home/vivek/docs/files/*.pdf
ls -l *.pdf
Linux rename a file syntax
In short, to rename a file:
mv file1 file2
You can get verbose output i.e. mv command can explain what is being done using the following syntax:
mv -v file1 file2
Sample outputs:
To make mv interactive pass the -i option. This option will prompt before overwriting file and recommended for new users:
mv -i file1 file2
Sample outputs:
How to use rename command to renames multiple files
The syntax is:
rename ‘s/old/new/’ files
rename [options] ‘s/old/new/’ files
For example, rename all perl files (*.perl) to *.pl, enter:
rename ‘s/perl/pl/’ *.perl
OR
rename -v ‘s/perl/pl/’ *.perl
Sample outputs:
The above command changed all files with the extension .perl to .pl. See “Howto Rename Multiple Files At a Shell Prompt In Linux or Unix” for more info.
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Detailed information about mv command
You can also view the manual page on mv using the following command:
man mv
OR
info mv
OR
man rename
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Как переименовать файл Linux
Переименование файла linux — очень простая операция, но для новичков в Linux эта задача может оказаться сложной. Также здесь есть несколько нюансов и возможностей, которые желательно знать уже опытным пользователям, например, массовое переименование. В графическом интерфейсе все делается очень просто, но настоящую гибкость дает терминал.
В этой статье мы рассмотрим как переименовать файл в Linux с помощью терминала, рассмотрим такие возможности, как массовое пакетное переименование файлов, а также регулярные выражения.
Как переименовать файл в Linux с помощью mv
В Linux существует замечательная стандартная утилита mv, которая предназначена для перемещения файлов. Но по своей сути перемещение — это то же самое, что и переименование файла linux, если выполняется в одной папке. Давайте сначала рассмотрим синтаксис этой команды:
$ mv опции файл-источник файл-приемник
Теперь рассмотрим основные опции утилиты, которые могут вам понадобиться:
- -f — заменять файл, если он уже существует;
- -i — спрашивать, нужно ли заменять существующие файлы;
- -n — не заменять существующие файлы;
- -u — заменять файл только если он был изменен;
- -v — вывести список обработанных файлов;
Чтобы переименовать файл linux достаточно вызвать утилиту без дополнительных опций. Просто передав ей имя нужного файла и новое имя:
mv file newfile
Как видите, файл был переименован. Вы также можете использовать полный путь к файлу или переместить его в другую папку:
mv /home/sergiy/test/newfile /home/sergiy/test/file1
Обратите внимание, что у вас должны быть права на запись в ту папку, в которой вы собираетесь переименовывать файлы. Если папка принадлежит другому пользователю, возможно, нужно будет запускать программу через sudo. Но в таком случае лучше запускать с опцией -i, чтобы случайно ничего не удалить.
Переименование файлов Linux с помощью rename
В Linux есть еще одна команда, которая позволяет переименовать файл. Это rename. Она специально разработана для этой задачи, поэтому поддерживает такие вещи, как массовое переименование файлов linux и использование регулярных выражений. Синтаксис утилиты тоже сложнее:
$ rename опции ‘s/ старое_имя / новое_имя ‘ файлы
$ rename опции старое_имя новое_имя файлы
В качестве старого имени указывается регулярное выражение или часть имени которую нужно изменить, новое имя указывает на что нужно заменить. Файлы — те, которые нужно обработать, для выбора файлов можно использовать символы подставки, такие как * или ?.
Рассмотрим опции утилиты:
- -v — вывести список обработанных файлов;
- -n — тестовый режим, на самом деле никакие действия выполнены не будут;
- -f — принудительно перезаписывать существующие файлы;
Например, переименуем все htm файлы из текущей папки в .html:
rename ‘s\.htm/\.html/’ *.htm
Или для изображений:
Символ звездочки означает, что переименование файлов linux будет выполнено для всех файлов в папке. В регулярных выражениях могут применяться дополнительные модификаторы:
- g (Global) — применять ко всем найденным вхождениям;
- i (Case Censitive) — не учитывать регистр.
Модификаторы размещаются в конце регулярного выражения, перед закрывающей кавычкой. Перед тем, как использовать такую конструкцию, желательно ее проверить, чтобы убедиться, что вы не допустили нигде ошибок, тут на помощь приходит опция -n. Заменим все вхождения DSC на photo в именах наших фотографий:
rename -n ‘s/DSC/photo/gi’ *.jpeg
Будут обработаны DSC, DsC и даже dsc, все варианты. Поскольку использовалась опция -n, то утилита только выведет имена изображений, которые будут изменены.
Можно использовать не только обычную замену, но и полноценные регулярные выражения чтобы выполнить пакетное переименование файлов linux, например, переделаем все имена в нижний регистр:
Из этого примера мы видим, что даже если такой файл уже существует, то он перезаписан по умолчанию не будет. Не забывайте использовать опцию -n чтобы ничего случайно не повредить.
Переименование файлов в pyRenamer
Если вы не любите использовать терминал, но вам нужно массовое переименование файлов Linux, то вам понравится утилита pyrenamer. Это графическая программа и все действия здесь выполняются в несколько щелчков мыши. Вы можете установить ее из официальных репозиториев:
sudo apt install pyrenamer
В окне программы вы можете видеть дерево файловой системы, центральную часть окна, где отображаются файлы, которые будут изменены, а также панель для указания параметров переименования.
Вы можете удалять или добавлять символы, переводить регистр, автоматически удалять пробелы и подчеркивания. У программы есть подсказки, чтобы сделать ее еще проще:
Опытным пользователям понравится возможность pyRenamer для переименования мультимедийных файлов из их метаданных. Кроме того, вы можете переименовать один файл если это нужно. Эта утилита полностью реализует функциональность mv и remove в графическом интерфейсе.
Выводы
В этой статье мы рассмотрели как переименовать файл в консоли linux. Конечно, есть и другие способы, например, написать скрипт, или использовать файловые менеджеры. А как вы выполняете сложные операции по переименованию? Напишите в комментариях!
Источник
Last Updated: October 16th, 2019 by Hitesh J in Guides, Linux
There are two ways to rename the files and directories in Linux-based operating systems. You can be done either using a GUI file manager or using a command-line interface. Generally, we use the mv command to rename the files and directories. But, the mv command won’t support multiple files and directories at once. mv command renames only one file at a time. In this case, you can use mv command with other commands to rename the multiple files at a time.
In this tutorial, we will explain how to rename files and directories in Linux-based operating systems.
Rename files with mv Command
A simple way to rename the files and directories is with mv command. It can move the file and directory from one name to another name.
The basic syntax of mv command is shown below:
mv [option] file1.txt file2.txt
Where file1.txt is the name of the source file and file2.txt is the name of the destination file.
mv [option] directory1 directory2
Where directory1 is the name of the source directory and directory2 is the name of the destination directory.
Let’s create a file named file1.txt and reneme it to file2.txt with mv command:
First, create a file named file1.txt:
Next, rename the file1.txt to file2.txt with mv command:
mv file1.txt file2.txt
Note : If you are login with normal user then mv command requires write permission for the folder containing the files
You can also use -v option to display the verbose output after running mv command.
For example, rename the file2.txt to file1.txt as shown below:
mv -v file2.txt file1.txt
You should see the following output:
You can use the -i option with mv command that will prompt before overwriting a file. This is very useful when the destination file is already exists.
Let’s rename the file1.txt to file2.txt with mv command:
mv -i file1.txt file2.txt
You will be prompt before overwriting file as shown below:
mv: overwrite ‘file2.txt’? y
Type y and hit enter to overwrite the file.
If you specify a file as source and directory as destination them mv command will move the source file to the destination directory.
For example, move the file1.txt to the directory /opt/ as hown below:
mv file1.txt /opt/
You can also use the following command to list all the options available with mv command:
You should see the following screen:
Rename multiple files with mv command
mv command won’t rename multiple files at a time. You will need to use other commands like find, for loop and while loop with mv command to achieve this.
For example, rename all the files with .txt extension in the current directory to the .php extension with find command as shown below:
First, create multiple files with .txt extension as shown below:
touch file1.txt file2.txt file3.txt file4.txt file5.txt
Next, rename all the files from .txt to .php extension with the following command:
find . -depth -name «*.txt» -exec sh -c ‘f=»<>«; mv — «$f» «$
In the above example, find command finds all the files with .txt extension in the current directory and use the mv command to rename the file with .php extension one by one using -exec switch.
You can also use “for loop” to rename all the files with .txt extension to the file with .php extension.
For example. run the following command to rename all the files from .txt to .php extension as shown below:
for file in *.txt; do mv — «$file» «$
Above command will create a for loop for all the files with .txt extension, rename all the files one by one with .php extension then complete the loop with done command.
Rename files with rename Command
The rename command is very advanced than move command. You can use rename command to rename single and multiple files according to the regular expression perlexpr. 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 Ubuntu/Debian systems:
apt-get install rename -y
On Centos/RHEL/Fedora, run the following command:
yum install prename -y
The basic syntax of rename command is shown below:
rename [options] perlexpr [filenames]
Run the following command to display all the information of rename command:
You should see the following screen:
Now, let’s start with some example. First, create some files with the following command:
touch file1.txt file2.txt file3.txt file4.txt file5.txt
Next, rename all the files with .txt extension to .html:
rename ‘s/.txt/.html/’ *.txt
You can use -v option with rename command to display names of files to be renamed along with their new names:
rename -v ‘s/.txt/.html/’ *.txt
You should see the following screen:
You can use -f option with rename command to allow existing files to be over-written.
rename -f ‘s/.txt/.html/’ *.txt
To convert all the files from lowercase to uppercase with the following command:
To convert all the files from uppercase lowercase with the following command:
Use -s with rename command to rename the files ignoring the symbolic links:
rename -s ‘s/.txt/.html/’ *.txt
Use -n option with rename command shows the files that will be changed without touching them:
rename -n ‘s/.txt/.html/’ *.txt
The above command wouldn’t actually rename the files but just print them in the console window.
Conclusion
In the above article, we learned in various ways you can rename files either single file or multiple files. I hope you have now enough knowledge of rename and mv command to rename files.
Источник