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) 🙂

Источник

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:

mv [options] [source] [destination]

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

Читайте также:  Чем отличается процесс от потока linux

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

mv [options] [current directory name] [new directory name]

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:

mv Directory1 Example_Directory

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:

rename [options] 's/[expression]/[replacement]/' [file name]

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:

rename 's/Directory1/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:

rename -v 's/Directory/Folder/' *
  • -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:

find . -depth -type d -name [current directory name] -execdir mv <> [new directory name] \;

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

Читайте также:  Linux good for games

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

find . -depth -type d -name Directory1 -execdir mv <> 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:

sudo nano rename_directories.sh

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

#!/bin/bash #Searches for directories and renames them according to the specified pattern for d in * do if [ -d "$d" ] then mv -- "$d" "_$(date +%Y%m%d)" fi done 
  • 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 .

Источник

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

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

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

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

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

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

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

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

Читайте также:  Linux can create thread

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 для всех папок в рабочей директории, в которой был он был запущен. Не забудьте дать скрипту права на выполнение перед тем, как будете его выполнять:

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.

Источник

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