Как переименовать файл в linux через терминал
Перейти к содержимому

Как переименовать файл в linux через терминал

  • автор:

Переименовываем файлы в Linux

как переименовать файл в linux

В любой операционной системе, будь то Linux или Windows, может появиться необходимость переименовать файл. И если с данной операцией пользователи Windows справляются без лишних проблем, то на Линуксe они могут столкнуться со сложностями, ввиду незнания системы и обилия множества способов. В этой статье будут перечислены все возможные вариации того, как можно переименовать файл в Linux.

Способ 1: pyRenamer

К сожалению, программное обеспечение pyRenamer не поставляется в стандартном наборе предустановок дистрибутива. Однако, как и все в Linux, его можно скачать и установить из официального репозитория. Команда для загрузки и установки следующая:

sudo apt install pyrenamer

После ее ввода укажите пароль и нажмите Enter. Далее необходимо будет подтвердить выполняемые действия. Для этого введите букву «Д» и нажмите снова Enter. Останется лишь подождать загрузки и установки (не закрывайте «Терминал» до завершения процесса).

После установки программу можно будет запустить, предварительно совершив поиск по системе с ее названием.

Основным отличием pyRenamer от менеджера файлов является то, что приложение способно взаимодействовать со множеством файлов одновременно. Она отлично подойдет в тех случаях, когда нужно поменять название сразу в нескольких документах, убрав какую-то часть или заменив ее на другую.

Давайте рассмотрим работу по переименованию файлов в программе:

  1. Открыв программу, вам необходимо проложить путь к директории, где находятся файлы, которые нужно переименовать. Делается это в левом рабочем окне (1). После определения директории в правом рабочем окне (2) будут показаны все файлы, находящиеся в ней. рабочие области в программе pyranamer в linux
  2. Далее необходимо перейти во вкладку «Substitutions». вкладка substitutions в программе pyrenamer в linux

После переименования можно спокойно закрывать программу и открывать файловый менеджер, чтобы проверить изменения.

На самом деле с помощью pyRenamer можно выполнить намного больше действий с файлами. Не только заменить одну часть имени на другую, но и, используя шаблоны во вкладке «Patterns», задать переменные, и, управляя ими, видоизменять названия файлов как угодно. Но подробно инструкцию нет смысла расписывать, так как при наведении курсора на активные поля высветится подсказка.

Способ 2: Терминал

К сожалению, не всегда получается переименовать файл с помощью специальных программ с графическим интерфейсом. Порою может возникнуть ошибка или что-то подобное, мешающее выполнению данной задачи. Но в Линуксe есть куда более одного способа выполнения поставленной задачи, поэтому переходим прямиком в «Терминал».

Команда mv

Команда mv в Линуксе отвечает за перемещение файлов из одной директории в другую. Но по своей сути перемещение файла схоже с переименованием. Так, используя эту команду, если переместить файл в ту же папку, в которой он находится, при этом задав новое имя, получится его переименовать.

Теперь давайте подробно разберемся с командой mv.

Синтаксис и опции команды mv

Синтаксис выглядит следующим образом:

mv опция оригинальное_имя_файла имя_файла_после_переименования

Чтобы пользоваться всеми возможностями данной команды, необходимо изучить ее опции:

Опция Действие
-i Запрашивать разрешении при замене существующих файлов
-f Заменять существующий файл без разрешения
-n Запретить замену существующего файла
-u Разрешить замену файла, если в нем присутствуют изменения
-v Показать все обработанные файлы (список)

После того как мы разобрались со всеми особенностями команды mv, можно приступать непосредственно к самому процессу переименования.

Примеры использования команды mv

Сейчас будет рассмотрена ситуация, когда в папке «Документы» находится файл с именем «Старый документ», наша задача переименовать его в «Новый документ», используя для этого команду mv в «Терминале». Для этого нам необходимо вписать:

mv -v «Старый документ» «Новый документ»

Примечание: чтобы операция прошла успешно, необходимо нужную папку открыть в «Терминале» и только после этого проводить все манипуляции. Открыть папку в «Терминале» можно при помощи команды cd.

переименовывание файла с помощью команды mv (1 способ)

Как можно видеть на изображении, нужный нам файл получил новое имя. Обратите внимание, что в «Терминале» указана опция «-v», которая строчкой ниже вывела подробный отчет о выполненной операции.

Также, используя команду mv, можно не только переименовать файл, но и попутно переместить его в другую папку. Как говорилось выше, данная команда именно для этого и нужна. Чтобы это сделать надо, помимо указания имени файла, прописать путь к нему.

Допустим, вы хотите из папки «Документы» переместить файл «Старый документ» в папку «Видео» попутно переименовав его в «Новый документ». Вот как будет выглядеть команда:

mv -v /home/user/Документы/»Старый документ» /home/user/Видео/»Новый документ»

Важно: если имя файла состоит из двух и более слов, его необходимо заключать в кавычки.

переименовывание файла с помощью команды mv (2 способ)

Примечание: если к папке, в которую вы собираетесь переместить файл, попутно переименовав его, у вас нет прав доступа, необходимо выполнять команду через суперпользователя, прописав в начале «super su» и введя пароль.

Команда rename

Команда mv хороша, когда необходимо переименовать один файл. И, безусловно, замены ей в этом не найти — она лучшая. Однако, если необходимо переименовать множество файлов или же заменить лишь часть имени, то фаворитом становится команда rename.

Синтаксис и опции команды rename

Как и с прошлой командой, для начала разберемся с синтаксисом rename. Выглядит он следующим образом:

rename опция ‘s/старое_имя_файла/новое_имя_файла/’ имя_файла

Как можно заметить, синтаксис намного сложнее, чем у команды mv, однако он позволяет выполнять больше действий с файлом.

Теперь давайте рассмотрим опции, они следующие:

Опция Действие
-v Показать обработанные файлы
-n Предварительный просмотр изменений
-f Принудительно переименовать все файлы

Теперь давайте рассмотрим наглядные примеры данной команды.

Примеры использования команды rename

Допустим, в директории «Документы» у нас есть множество файлов с названием «Старый документ num», где num — это порядковый номер. Наша задача, используя команду rename, во всех этих файлах изменить слово «Старый» на «Новый». Для этого нам необходимо выполнить следующую команду:

rename -v ‘s/Старый/Новый/’ *

где, «*» — все файлы в указанной директории.

Примечание: если вы хотите провести изменение в одном файле, то вместо «*» пропишите его имя. Не забывайте, если имя состоит из двух и более слов, то его необходимо брать в кавычки.

переименовывание множества файлов с помощью команды rename в терминале линукс

Примечание: с помощью данной команды можно запросто изменить расширения файлов, указав изначально старое расширения, записав его, например, в виде «\.txt», а затем новое, например, «\.html».

С помощью команды rename также можно менять регистр текста имени. Например, мы хотим файлы с именем «NEW FILE (num)» переименовать в «new file (num)». Для этого нужно прописать следующую команду:

изменение регистра в имени файлов с помощью команды rename в терминале линукс

Примечание: если необходимо поменять регистр в имени файлов на русском, то используйте команду «rename -v ‘y/А-Я/а-я/’ *».

Способ 3: Файловый менеджер

К сожалению, в «Терминале» не всякий пользователь сможет разобраться, поэтому будет разумно рассмотреть способ переименования файлов с использованием графического интерфейса.

Взаимодействие с файлами в Linux хорошо осуществлять при помощи менеджера файлов, будь то Nautilus, Dolphin или любой другой (зависит от дистрибутива Linux). Он позволяет визуализировать не только файлы, но и директории, а также каталоги, выстраивая их иерархию в том виде, который более понятен неопытному пользователю. В таких менеджерах легко сможет сориентироваться даже новичок, который только-только установил себе Linux.

Переименовать файл при помощи файлового менеджера просто:

  1. Для начала вам необходимо открыть сам менеджер и перейти в ту директорию, где расположен файл, нуждающийся в переименовании. переход в нужную директорию в файловом менеджере nautilus в linux
  2. Теперь необходимо навести курсор на него и нажать левую кнопку мыши (ЛКМ), чтобы выделить. После чего клавишу F2 или правую клавишу мыши и выбрать пункт “Переименовать”. переименование файла в линукс в файловом менеджере linux
  3. Под файлом появится форма для заполнения, а само имя файла станет выделенным. Вам остается лишь ввести необходимое название и нажать клавишу Enter для подтверждения изменений.

Вот так просто и быстро можно переименовать файл в Линуксe. Представленная инструкция работает во всех файловых менеджерах различных дистрибутивов, однако могут быть различия в наименовании каких-то элементов интерфейса или в их отображении, но общий смысл действий остается одинаковым.

Заключение

По итогу можно сказать, что способов переименовать файлы в Linux много. Все они в достаточной мере отличаются друг от друга и имеют важность в различных ситуациях. Например, если вам необходимо переименовывать одиночные файлы, то лучше использовать файловый менеджер системы или же команду mv. А в случае с частичным или множественным переименовыванием отлично подойдет программа pyRenamer или команда rename. Вам осталось лишь одно — определиться, каким способом пользоваться.

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 your OS, you will need to have strong knowledge of the fundamentals – simple Linux 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.

Learn More Linux Commands for File Management

How to Rename Files In Linux FAQ

What Linux Command Lets You Rename Files?

Use the move (mv) command on Linux to rename files and folders. The system understands renaming files as moving the file or folder from one name to another, hence why the mv command can be used for renaming purposes, too.

How Do You Rename Multiple Files In Linux?

You can rename multiple files in Linux in many ways. You can batch rename by using mmv, bulk rename files with the rename utility, use renameutils or vimv, or use Emacs or Thunar file manager to execute the task.

Edward is a content editor with years of experience in IT writing, marketing, and Linux system administration. His goal is to encourage readers to establish an impactful online presence. He also really loves dogs, guitars, and everything related to space.

How to rename a file in Terminal? [duplicate]

How do I rename my_static to static and remove static (2)?

2 Answers 2

That command is used for moving and renaming files and directories.

Nikola K.'s user avatar

A simple way to rename files and folders is with the mv command (shortened from “move”). Its primary purpose is moving files and folders, but it can also rename them since the act of renaming a file is interpreted by the filesystem as moving it from one name to another.

where “file1.ext” is the “old” name of the file, and “file2.ext” the new name.

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.

Let us explain with the help of an example. Here, we want to rename all .txt extension files of the current directory replaced with another .html extension. In this case, the following code will help us:

The above code will iterate using for loop through the files list having the .txt extension. After that, in the second line, it will replace each file extension .txt with .html. In the end, ‘done’ indicated the end of the for loop segment.

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

In the following example, we want to change the extension of all text files. So, we will change or replace all files with extension .txt to .html by executing the following command:

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:

By default, the rename command does not overwrite an existing file. However, if you pass option -f along with the rename command then, it will help you to overwrite the existing files. Execute the following command to use the rename command followed by the -f option:

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.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *