Renaming folder on linux

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?

7 Answers 7

mv /home/user/oldname /home/user/newname 

This will not work if the new name is already an existing directory. Instead, it will move the old directory inside the new one.

If the directory name is the same with capitalization you will get No such file or directory . To avoid this do something like mv /home/user/Folder /home/user/temp; mv /home/user/temp/ /home/user/folder .

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.

mv -T /home/user/oldname /home/user/newname 

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.

mv /home/user/oldname /home/user/newname 

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

Doesn’t work if you want to capitalize the directory name in a case-insensitive filesystem (likely on MacOS). mv -T $PWD/analisys $PWD/Analisys returns mv: ‘/Users/sixtykeys/Projects/murphy/tmp/analisys’ and ‘/Users/sixtykeys/Projects/murphy/tmp/Analisys’ are the same file . I worked around this by using an intermediate name (i.e. analisys_ ).

The command may not have been successful due to the limitations of the filesystem, but from another perspective it was successful in interpreting your intentions (renaming a directory, not moving it) 🙂

Источник

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

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

Читайте также:  Google chrome deb linux

Можно переименовать не просто одну папку, а выбрать стразу несколько и настроить для них массовое переименование. Вы можете использовать команду mv, rename, а также утилиту find для массового переименования. Но сначала давайте поговорим о том как всё это сделать в файловом менеджере.

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

1. Файловый менеджер

Самый простой способ переименовать папку — в файловом менеджере. Например, для Ubuntu это Nautilus. Откройте файловый менеджер и кликните правой кнопкой мыши по нужной папке. В контекстном меню выберите Переименовать:

Затем просто введите новое имя:

После нажатия клавиши Enter папка будет переименована.

2. Команда mv

Команда mv предназначена для перемещения файлов в другое место, однако её можно без проблем использовать чтобы переименовать папку или файл не перемещая его никуда. По сути, если файл или папка перемещается в пределах одного раздела диска, то на самом деле они просто переименовываются, а физически остаются на том же месте. Синтаксис:

$ mv старое_имя новое_имя

Чтобы переименовать папку ~/Музыка/Папка 1 в Папка 11 используйте:

mv ~/Музыка/Папка_1 ~/Музыка/Папка_10

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

Обратите внимание, что слеш в конце папки назначения писать нельзя, иначе, ваша папка будет перемещена в указанную папку, если такая существует.

3. Команда rename

Команду rename можно использовать аналогично mv, только она предназначена специально для переименования файлов и папок поэтому у неё есть несколько дополнительных возможностей. Синтаксис команды следующий:

$ rename регулярное_выражение файлы

Но прежде всего программу надо установить:

Самый простой пример, давайте заменим слово «Папка» на «Dir» во всех папках:

Можно пойти ещё дальше и использовать регулярное выражение чтобы заменить большие буквы в названиях на маленькие:

Чтобы не выполнять действия, а только проверить какие папки или файлы собирается переименовывать команда используйте опцию -n:

4. Скрипт Bash

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

#!/bin/bash
for dir in *
do
if [ -d «$dir» ]
then
mv «$» «$_new»
fi
done

Этот скрипт добавляет слово _new для всех папок в рабочей директории, в которой был он был запущен. Не забудьте дать скрипту права на выполнение перед тем, как будете его выполнять:

Читайте также:  Параметры модуля ядра linux

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:

gio move ~/Музыка/Dir_3 ~/Музыка/Dir_33

Переименование папки Linux выполняется аналогично тому, как это делается с помощью mv.

Выводы

В этой небольшой статье мы рассмотрели как переименовать папку Linux. Как видите, для этого существует множество способов и всё делается достаточно просто.

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

Источник

Rename a file or folder

As with other file managers, you can use Files to change the name of a file or folder.

To rename a file or folder:

  1. Right-click on the item and select Rename , or select the file and press F2 .
  2. Type the new name and press Enter or click Rename .

You can also rename a file from the properties window.

When you rename a file, only the first part of the name of the file is selected, not the file extension (the part after the last . ). The extension normally denotes what type of file it is (for example, file.pdf is a PDF document), and you usually do not want to change that. If you need to change the extension as well, select the entire file name and change it.

If you renamed the wrong file, or named your file improperly, you can undo the rename. To revert the action, immediately click the menu button in the toolbar and select Undo Rename , or press Ctrl + Z , to restore the former name.

Читайте также:  Phpmyadmin установка alt linux

Valid characters for file names

You can use any character except the / (slash) character in file names. Some devices, however, use a file system that has more restrictions on file names. Therefore, it is a best practice to avoid the following characters in your file names: | , \ , ? , * , < , " , : , >, / .

If you name a file with a . as the first character, the file will be hidden when you attempt to view it in the file manager.

Common problems

You cannot have two files or folders with the same name in the same folder. If you try to rename a file to a name that already exists in the folder you are working in, the file manager will not allow it.

File and folder names are case sensitive, so the file name File.txt is not the same as FILE.txt . Using different file names like this is allowed, though it is not recommended.

The file name is too long

On some file systems, file names can have no more than 255 characters in their names. This 255 character limit includes both the file name and the path to the file (for example, /home/wanda/Documents/work/business-proposals/… ), so you should avoid long file and folder names where possible.

The option to rename is grayed out

If Rename is grayed out, you do not have permission to rename the file. You should use caution with renaming such files, as renaming some protected files may cause your system to become unstable. See Set file permissions for more information.

More Information

You can choose the displayed language by adding a language suffix to the web address so it ends with e.g. .html.en or .html.de.
If the web address has no language suffix, the preferred language specified in your web browser’s settings is used. For your convenience:
[ Change to English Language | Change to Browser’s Preferred Language ]

The material in this document is available under a free license, see Legal for details.
For information on contributing see the Ubuntu Documentation Team wiki page. To report errors in this documentation, file a bug.

Источник

Оцените статью
Adblock
detector