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

от admin

Переименование файла или папки

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

Чтобы переименовать файл или папку:

Нажмите на объект правой кнопкой и выберите Переименовать или выберите файл и нажмите клавишу F2 .

Наберите новое имя и нажмите Enter или кнопку Переименовать .

Можно также переименовать файл из окна его свойств .

При переименовании файла выделяется только начало его имени, без расширения (части после . ). Расширение показывает тип файла (например, file.pdf — это документ PDF), и менять его обычно нет необходимости. Если нужно изменить и расширение, выделите имя файла целиком и измените его.

Если вы переименовали не тот файл, или дали ему неправильное имя, можно отменить переименование. Для этого немедленно нажмите кнопку меню в панели инструментов и выберите Переименовать или нажмите Ctrl + Z , чтобы вернуть прежнее имя файла.

Символы, допустимые в именах файлов

В именах файлов можно использовать любые символы, кроме / (слеш). Однако на некоторых устройствах используется файловая система с дополнительными ограничениями на имена файлов. Поэтому рекомендуется избегать использования следующих символов в именах файлов: | , \ , ? , * , < , » , : , > , / .

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

Типичные проблемы

Нельзя поместить два файла с одинаковым именем в одну и ту же папку. Менеджер файлов не позволит переименовать файл, если такое имя уже существует в этой папке.

Имена файлов и папок чувствительны к регистру символов, поэтому File.txt и FILE.txt — это два разных имени. Использовать имена файлов, различающиеся только регистром символов разрешается, но не рекомендуется.

Слишком длинное имя файла

В некоторых файловых системах имена файлов не могут содержать более 255 символов. Это ограничение в 255 символов включает в себя как собственно имя файла, так и путь к файлу (например, /home/wanda/Documents/work/business-proposals/… ), поэтому по возможности следует избегать длинных имён файлов и папок.

Команда переименования неактивна

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

Дополнительная информация

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.

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

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.

How to Rename a Directory in Linux

Renaming a directory is one of the most basic tasks you will perform on any operating system. The Linux terminal offers several different ways to rename directories using commands and scripts.

In this tutorial, we will go over the different methods you can use to rename a directory in Linux through the terminal window.

How to rename directories in Linux

  • A system running a Linux distribution
  • An account with sudo privileges
  • Access to the terminal window/command line
  • Access to a text editor, such as Vim or Nano

Renaming Directories With the mv Command

The primary function of the mv command in Linux is moving files and directories from one place to another. It uses the following command syntax:

Note: To learn more about using the mv command, check out our guide to moving directories in Linux.

If the destination directory does not exist, the mv command renames the source directory instead. In this case, the syntax changes to:

As an example, let’s say we have Directory1, Directory2, and Directory3 in our Home directory:

Checking the content of the Home directory using the ls command

To rename Directory1 into Example_Directory with the mv command, use:

There is no output if the command is successful, so we need to use the ls command to verify the name change:

Verifying the name change using the ls command

Renaming Directories With the rename Command

The rename command in Linux is a dedicated command used to change the names of files and directories. Using this command makes it easier to rename multiple directories at the same time.

Note: The rename command is not included in all Linux distributions by default. If your system is missing the rename command, install it with:

  • For Ubuntu and Debian, use sudo apt install rename
  • For CentOS and Fedora, use sudo yum install prename
  • For Arch Linux, use sudo pacman -S rename

Renaming a Single Directory With the rename Command

The rename command uses the following syntax:

The command renames the file by replacing the first occurrence of the expression with the replacement. For example, if we want to rename Directory1 to Example_Directory:

In this example, we can see that the rename command syntax consists of several sections:

  • rename : Invokes the rename command.
  • s : Short for substitute, indicates that we are replacing the expression with the replacement.
  • / Directory1 : Specifies the expression or the part of the old directory name that you want to replace.
  • /Example_Directory /: Defines the replacement or the new directory name.
  • * : Searches the Home directory for names matching the provided expression.

Verifying the Home directory content with the ls command shows that the directory now has a new name:

Verifying the new directory name with the ls command

Renaming Multiple Directories With the rename Command

The rename command provides a way to rename multiple directories at the same time without using bash scripts. For instance, if we want to rename Directory1, Directory2, and Directory3 to Folder1, Folder2, and Folder3:

In the example above:

  • -v : Invokes the verbose output, listing each step of the process.
  • 's/Directory/Folder/' : Replaces Directory in the names of the search results with Folder.
  • * : Searches the Home directory for names matching the provided expression.

Using the rename command to change multiple directory names

The rename command can also translate file names by using the y argument instead of the s argument. In this case, it translates one string of characters into another, character-for-character.

The command above translates every a character into d, every b into e, and every c into f.

In the example below, we translated blank spaces in directory names to underscores (_).

Translating directory names using the rename command

Renaming Directories With the find Command

In case you are not sure where the directory you want to rename is located, using the find command with the mv command lets you search for it and rename it when it’s found:

In the example above, -execdir executes the mv command once the find command locates the directory.

For instance, the command below finds and renames Directory1 into Example_Directory:

Using the find command to rename a directory

Renaming Directories With Bash Scripts

Using bash scripts is another way of renaming multiple directories at the same time. Unlike the rename command, bash scripts allow you to save a template for future use.

Start by creating the script with a text editor, such as Nano:

The following example is a bash script that searches for directories and appends the current date to their name:

In the example above:

  • The first line instructs the script to go through all files and directories in the current location.
  • Lines 2 and 3 check for directories.
  • Lines 4 and 5 append the current date to the name of any directory found.

Press Ctrl+X, type Y, and press Enter to close and save the script.

As an example, let’s use the script above to change the names of Directory1, Directory2, and Directory3, located in the Example directory.

Start by moving in to the Example directory:

Learn more about Linux cd command in our guide on how to change and move to different categories.

Next, execute the script by using the sh command:

Using the ls command allows us to verify the name change:

Using the ls command to verify the name change

After reading this article, you should know how to rename directories in Linux using commands and bash scripts.

Learn more about using Linux commands in our Linux Commands All Users Should Know .

Похожие статьи