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

Как переименовать папку в linux в терминале

  • автор:

Как переименовать каталоги в Linux

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

В этой статье объясняется, как переименовывать каталоги с помощью командной строки.

Переименование каталогов

В Linux и Unix-подобных операционных системах вы можете использовать команду mv (сокращение от move) для переименования или перемещения файлов и каталогов из одного места в другое.

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

Например, чтобы переименовать каталог dir1 в dir2 вы должны запустить:

При переименовании каталогов вы должны указать ровно два аргумента для команды mv . Первый аргумент — это текущее имя каталога, а второй — новое имя.

Важно отметить, что если dir2 уже существует, dir1 перемещается в каталог dir2 .

Чтобы переименовать каталог, которого нет в текущем рабочем каталоге, необходимо указать абсолютный или относительный путь:

Переименование нескольких каталогов

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

Одновременное переименование нескольких каталогов требуется редко.

Переименование нескольких каталогов с помощью mv

Команда mv может переименовывать только один файл за раз. Однако его можно использовать в сочетании с другими командами, такими как find или внутренние циклы, для одновременного переименования нескольких файлов.

Вот пример, показывающий, как использовать цикл for в Bash for добавления текущей даты к именам всех каталогов в текущем рабочем каталоге:

Давайте проанализируем код построчно:

  • Первая строка создает цикл и выполняет итерацию по списку всех файлов.
  • Вторая строка проверяет, является ли файл каталогом.
  • Третья строка добавляет текущую дату в каждый каталог.

Вот решение той же задачи с использованием mv в сочетании с find :

Команда find передает все каталоги в mv один за другим с помощью параметра -exec . Строка <> — это имя обрабатываемого в данный момент каталога.

Как вы можете видеть из примеров, переименование нескольких каталогов с помощью mv — непростая задача, поскольку для этого требуется хорошее знание сценариев Bash.

Переименование нескольких каталогов с rename

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

Есть две версии команды rename с разным синтаксисом. Мы будем использовать Perl-версию команды rename . Файлы переименовываются в соответствии с заданным регулярным выражением Perl .

В следующем примере показано, как заменить пробелы в именах всех каталогов в текущем рабочем каталоге символами подчеркивания:

На всякий случай передайте параметр -n для rename чтобы выводить имена переименовываемых каталогов без их переименования.

Вот еще один пример, показывающий, как преобразовать имена каталогов в нижний регистр:

Выводы

Мы показали вам, как использовать команды mv для переименования каталогов.

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

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 do I rename a directory via the command line?

I have got the directory /home/user/oldname and I want to rename it to /home/user/newname . How can I do this in a terminal?

Rafał Cieślak's user avatar

7 Answers 7

Rafał Cieślak's user avatar

mv can do two jobs.

  1. It can move files or directories
  2. It can rename files or directories

To just rename a file or directory type this in Terminal:

with space between the old and new names.

To move a file or directory type this in Terminal.

it will move the file to the desktop.

Zanna's user avatar

That will rename the directory if the destination doesn’t exist or if it exists but it’s empty. Otherwise it will give you an error.

If you do this instead:

One of two things will happen:

  • If /home/user/newname doesn’t exist, it will rename /home/user/oldname to /home/user/newname
  • If /home/user/newname exists, it will move /home/user/oldname into /home/user/newname , i.e. /home/user/newname/oldname

If you want to rename a directory at your level in the file system (e.g., you are at your home directory and want to rename a directory that is also in your home directory):

This gvfs-move command will also rename files and directories.

gvfs-rename will rename directories as well. It will give an error if a directory with the new name already exists. The only limitation is that you can’t use a path with the folder name. So

will not work, but

will work. Not as useful as mv -T but I read in the man that it was meant for network operations.

Как переименовать папку 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 «$

» «$_new»
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. Как видите, для этого существует множество способов и всё делается достаточно просто.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

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

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