Переименовать папку в Linux не намного сложнее, чем переименовать файл. Вы можете сделать это в графическом интерфейсе или с в терминале с помощью нескольких команд. Как и для других задач в Linux для этой существует множество способов решения.
Можно переименовать не просто одну папку, а выбрать стразу несколько и настроить для них массовое переименование. Вы можете использовать команду mv, rename, а также утилиту find для массового переименования. Но сначала давайте поговорим о том как всё это сделать в файловом менеджере.
1. Файловый менеджер
Самый простой способ переименовать папку — в файловом менеджере. Например, для Ubuntu это Nautilus. Откройте файловый менеджер и кликните правой кнопкой мыши по нужной папке. В контекстном меню выберите Переименовать:
Затем просто введите новое имя:
После нажатия клавиши Enter папка будет переименована.
2. Команда mv
Команда mv предназначена для перемещения файлов в другое место, однако её можно без проблем использовать чтобы переименовать папку или файл не перемещая его никуда. По сути, если файл или папка перемещается в пределах одного раздела диска, то на самом деле они просто переименовываются, а физически остаются на том же месте. Синтаксис:
$ mv старое_имя новое_имя
Чтобы переименовать папку ~/Музыка/Папка 1 в Папка 11 используйте:
mv ~/Музыка/Папка_1 ~/Музыка/Папка_10
Если в имени файлов есть пробелы, то путь к файлу следует взять в кавычки. После выполнения этой команды папка будет переименована:
ls ~/Музыка
Обратите внимание, что слеш в конце папки назначения писать нельзя, иначе, ваша папка будет перемещена в указанную папку, если такая существует.
3. Команда rename
Команду rename можно использовать аналогично mv, только она предназначена специально для переименования файлов и папок поэтому у неё есть несколько дополнительных возможностей. Синтаксис команды следующий:
$ rename регулярное_выражение файлы
Но прежде всего программу надо установить:
sudo apt install rename
Самый простой пример, давайте заменим слово «Папка» на «Dir» во всех папках:
rename 's/Папка/Dir/' ~/Музыка/*
Можно пойти ещё дальше и использовать регулярное выражение чтобы заменить большие буквы в названиях на маленькие:
rename 'y/A-Z/a-z/' ~/Музыка/*
Чтобы не выполнять действия, а только проверить какие папки или файлы собирается переименовывать команда используйте опцию -n:
rename -n 'y/A-Z/a-z/' ~/Музыка/*
4. Скрипт Bash
Для массового переименования папок можно использовать скрипт на Bash с циклом for, который будет перебирать все папки в директории и делать с ними то, что нужно. Вот сам скрипт:
vi dir_rename.sh
#!/bin/bash
for dir in *
do
if [ -d "$dir" ]
then
mv "${dir}" "${dir}_new"
fi
done
Этот скрипт добавляет слово _new для всех папок в рабочей директории, в которой был он был запущен. Не забудьте дать скрипту права на выполнение перед тем, как будете его выполнять:
chmod ugo+x dir_rename.sh
./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:
gio move ~/Музыка/Dir_3 ~/Музыка/Dir_33
Переименование папки Linux выполняется аналогично тому, как это делается с помощью mv.
Выводы
В этой небольшой статье мы рассмотрели как переименовать папку Linux. Как видите, для этого существует множество способов и всё делается достаточно просто.
Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .
Об авторе
Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.
Introduction
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.
Prerequisites
- 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]
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:
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:
ls -l
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 therename
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:
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/' *
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.
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.
For instance:
rename 'y/abc/def/'
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 (_).
rename -v 'y/ /_/' *
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.
For instance, the command below finds and renames Directory1 into Example_Directory:
find . -depth -type d -name Directory1 -execdir mv {} Example_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" "{d}_$(date +%Y%m%d)"
fi
done
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:
cd Example
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:
sh rename_directory.sh
Using the ls
command allows us to verify the name change:
ls -l
Conclusion
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 {Ultimate List}.
Переименование каталогов — одна из самых основных операций, которые вам часто приходится выполнять в системе Linux. Вы можете переименовывать каталоги из файлового менеджера графического интерфейса с помощью пары щелчков мышью или с помощью терминала командной строки.
В этой статье объясняется, как переименовывать каталоги с помощью командной строки.
Переименование каталогов
В Linux и Unix-подобных операционных системах вы можете использовать команду mv
(сокращение от move) для переименования или перемещения файлов и каталогов из одного места в другое.
Синтаксис команды mv
для перемещения каталогов следующий:
mv [OPTIONS] source destination
Например, чтобы переименовать каталог dir1
в dir2
вы должны запустить:
mv dir1 dir2
При переименовании каталогов вы должны указать ровно два аргумента для команды mv
. Первый аргумент — это текущее имя каталога, а второй — новое имя.
Важно отметить, что если dir2
уже существует, dir1
перемещается в каталог dir2
.
Чтобы переименовать каталог, которого нет в текущем рабочем каталоге, необходимо указать абсолютный или относительный путь:
mv /home/user/dir1 /home/user/dir2
Переименование нескольких каталогов
Переименование одного каталога — простая задача, но переименование сразу нескольких каталогов может быть проблемой, особенно для новых пользователей Linux.
Одновременное переименование нескольких каталогов требуется редко.
Переименование нескольких каталогов с помощью mv
Команда mv
может переименовывать только один файл за раз. Однако его можно использовать в сочетании с другими командами, такими как find
или внутренние циклы, для одновременного переименования нескольких файлов.
Вот пример, показывающий, как использовать цикл for
в Bash for
добавления текущей даты к именам всех каталогов в текущем рабочем каталоге:
for d in *; do
if [ -d "$d" ]; then
mv -- "$d" "${d}_$(date +%Y%m%d)"
fi
done
Давайте проанализируем код построчно:
- Первая строка создает цикл и выполняет итерацию по списку всех файлов.
- Вторая строка проверяет, является ли файл каталогом.
- Третья строка добавляет текущую дату в каждый каталог.
Вот решение той же задачи с использованием mv
в сочетании с find
:
find . -mindepth 1 -prune -type d -exec sh -c 'd="{}"; mv -- "$d" "${d}_$(date +%Y%m%d)"' ;
Команда find
передает все каталоги в mv
один за другим с помощью параметра -exec
. Строка {}
— это имя обрабатываемого в данный момент каталога.
Как вы можете видеть из примеров, переименование нескольких каталогов с помощью mv
— непростая задача, поскольку для этого требуется хорошее знание сценариев Bash.
Переименование нескольких каталогов с rename
Команда rename
используется для переименования нескольких файлов и каталогов. Эта команда более сложна, чем mv
поскольку требует базовых знаний регулярных выражений.
Есть две версии команды rename
с разным синтаксисом. Мы будем использовать Perl-версию команды rename
. Файлы переименовываются в соответствии с заданным регулярным выражением Perl .
В следующем примере показано, как заменить пробелы в именах всех каталогов в текущем рабочем каталоге символами подчеркивания:
find . -mindepth 1 -prune -type d | rename 'y/ /_/'
На всякий случай передайте параметр -n
для rename
чтобы выводить имена переименовываемых каталогов без их переименования.
Вот еще один пример, показывающий, как преобразовать имена каталогов в нижний регистр:
find . -mindepth 1 -prune -type d | rename 'y/A-Z/a-z/'
Выводы
Мы показали вам, как использовать команды mv
для переименования каталогов.
Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.
Переименование файлов в Linux можно выполнять средствами графических программ, а также через командную строку. Можно переименовать один файл, а можно сразу группу файлов — массовое переименование. Рассмотрим различные способы, с помощью которых можно переименовывать файлы в Linux.
Переименование командой mv
Команда mv (от слова move) используется для переименования или перемещения файлов и директорий из командной строки.
Синтаксис команды mv очень простой:
mv опции источник назначение
источник — файл(ы) или директория, которую необходимо переместить или переименовать.
назначение — файл или директория, в которую будет перемещен источник.
Основные опции:
-f — перезаписывать существующие файлы.
-n — не перезаписывать существующие файлы.
-i — выдавать запрос на перезапись существующих файлов.
-u — не перемещать файлы, которые уже существуют, если существующие файлы новее (время модификации новее).
-v — выводить имя каждого файла перед его переносом.
Как задавать имена файлов и директорий для переименования:
- Чтобы переименовать файл с помощью команды mv нужно в качестве источника задать данный файл, а в качестве назначения указать новое имя файла.
- Если указывается путь до файла, то директории должны совпадать, иначе файл будет перемещен в другую директорию.
- Если в качестве источника указать файл, а в качестве назначения путь до файла в другой директории и задать новое имя файла, то файл будет перемещен в другую директорию и переименован.
- Если в качестве источника указана директория, а в качестве назначения задано новое имя для данной директории, то директория будет просто переименована. Если же директория назначения уже существует, то директория источник будет перемещена в директорию назначения.
Рассмотрим примеры.
Переименование файла
Переименование файла myfile1.dat в файл myfile2.dat:
mv myfile1.dat myfile2.dat
Переименование файла с указанием пути до файла:
mv /home/pingvinus/myfile1.dat /home/pingvinus/myfile2.dat
Переименование директории
Переименование директории /home/pingvinus/mydir1 в директорию /home/pingvinus/mydir2. Справедливо, если /home/pingvinus/mydir2 не существует.
mv /home/pingvinus/mydir1 /home/pingvinus/mydir2
Если /home/pingvinus/mydir2 существует, то, выполнив команду:
mv /home/pingvinus/mydir1 /home/pingvinus/mydir2
директория mydir1 будет перемещена внутрь директории /home/pingvinus/mydir2. То есть mydir1 будет в результате находиться по адресу /home/pingvinus/mydir2/mydir1.
Переименование и перемещение
Если в качестве файла назначения указан новый путь и новое имя файла, то файл будет перемещен и переименован. Например, следующая команда перемещает файл myfile1.dat в директорию /home/pingvinus/dir и переименовывает его в myfile2.dat:
mv /home/pingvinus/myfile1.dat /home/pingvinus/dir/myfile2.dat
Переименование командой rename
Команда rename служит для массового (пакетного) переименования файлов. Она позволяет выполнять замену определенных символов или частей имени файла и использованием Perl-регулярных выражений.
Если вдруг в вашем дистрибутиве нет команды rename, то ее можно установить, выполнив (выберите соответствующую команду для вашего дистрибутива):
sudo apt install rename
sudo yum install prename
yaourt -S perl-rename
Синтаксис команды rename:
rename опции ’s/старое_имя/новое_имя’ файлы
старое_имя — регулярное выражение или часть имени файла, которое нужно заменить на новое_имя.
новое_имя — задает результирующее имя файла (может быть регулярным выражением).
Основные опции:
-f — перезаписывать существующие файлы.
-n — вывести список файлов, которые будут переименованы и их новые имена, но не выполнять переименование.
-v — вывести список обработанных файлов.
Проще всего понять, как пользоваться данной командой, на примерах.
Изменение расширения файлов
Массово изменить расширение .html на .php у всех html-файлов.
rename 's/.html/.php/' *.html
По умолчанию rename не перезаписывает существующие файлы. Чтобы существующие файлы перезаписывались, используется опция -f:
rename -f 's/.html/.php/' *.html
Замена пробелов на подчеркивание
Заменить все символы пробелов в имени файлов на символ подчеркивания:
rename 'y/ /_/' *
Конвертация имен файлов в строчные буквы
rename 'y/A-Z/a-z/' *
Конвертация имен файлов в прописные буквы
rename 'y/a-z/A-Z/' *
Показать, что именно будет переименовано, но не переименовывать
Чтобы избежать ошибок при переименовании файлов, особенно при использовании сложных регулярных выражений, можно сначала вывести список того, что будет переименовано, но не запускать само переименование. Для этого служит опция -n.
Например, мы хотим изменить расширение у файлов с .jpeg на .jpg. Используем опцию -n, чтобы просто вывести какие файлы будут переименованы:
rename -n 's/.jpeg$/.jpg/' *
Полное описание команд mv и rename можно получить, выполнив в терминале команды:
man mv
man rename
Массовое переименование с использованием программ
Для массового переименования файлов можно воспользоваться программами:
- pyRenamer
- GPRename
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?
asked Aug 8, 2011 at 16:58
3
mv /home/user/oldname /home/user/newname
answered Aug 8, 2011 at 17:10
Rafał CieślakRafał Cieślak
19.9k7 gold badges54 silver badges86 bronze badges
7
mv
can do two jobs.
- It can move files or directories
- It can rename files or directories
To just rename a file or directory type this in Terminal:
mv old_name new_name
with space between the old and new names.
To move a file or directory type this in Terminal.
mv file_name ~/Desktop
it will move the file to the desktop.
Zanna♦
68.3k55 gold badges210 silver badges320 bronze badges
answered Apr 21, 2013 at 13:58
shadishadi
1,5591 gold badge9 silver badges2 bronze badges
0
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.
If you do this instead:
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
Source: How to decide that mv moves into a directory rather than replacing directory?
answered Apr 27, 2016 at 18:31
bmaupinbmaupin
4,56742 silver badges67 bronze badges
3
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):
mv Directory ./NewNameDirectory
answered Jul 12, 2014 at 13:26
Matt PMatt P
1111 silver badge2 bronze badges
This gvfs-move
command will also rename files and directories.
gvfs-move /home/user/oldname /home/user/newname
answered Apr 21, 2014 at 5:26
Avinash RajAvinash Raj
75.8k55 gold badges212 silver badges252 bronze badges
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
gvfs-rename /home/boo /home/boo-the-dog
will not work, but
cd /home
gvfs-rename boo boo-the-dog
will work. Not as useful as mv -T but I read in the man that it was meant for network operations.
answered Nov 29, 2016 at 7:58
thebunnyrulesthebunnyrules
1,0331 gold badge12 silver badges18 bronze badges
My preferred method is using: vidir because I love vi
Install moreutils
sudo apt update; sudo apt install moreutils
Call command vidir in your home-directory
vidir ~
Now search for the directory to change, using slash / e.g. /oldname
make the changes, then press =
ESC
type :wq
Done!
answered Jun 16, 2022 at 17:04
koni_raidkoni_raid
3,2622 gold badges22 silver badges28 bronze badges
В этом уроке мы покажем вам , как использовать mv и rename команды для переименования файлов и каталогов.
Переименование файлов и каталогов является одной из самых основных задач, которые вам часто приходится выполнять в системе Linux. Вы можете переименовывать файлы, используя файловый менеджер с графическим интерфейсом или через терминал командной строки.
Переименовать один файл легко, но переименование нескольких файлов одновременно может быть проблемой, особенно для пользователей, которые являются новичками в Linux.
Переименование файлов с помощью mv
команды
mv
Команда ( не хватает хода) используется для переименования или перемещения файлов из одного места в другое. Синтаксис mv
команды следующий:
mv [OPTIONS] source destination
source
Может быть один или несколько файлов или каталогов и destination
может быть один файл или каталог.
- Если вы указываете несколько файлов как
source
,destination
должен быть каталог. В этом случаеsource
файлы перемещаются в целевой каталог. - Если вы указываете один файл как
source
, аdestination
целью является существующий каталог, то файл перемещается в указанный каталог. - Чтобы переименовать файл, вам нужно указать один файл как
source
и один файл какdestination
цель.
Например, чтобы переименовать файл так, file1.txt
как file2.txt
вы запустите:
mv file1.txt file2.txt
Переименование нескольких файлов с помощью mv
команды
Команда mv
может переименовывать только один файл за раз, но ее можно использовать вместе с другими командами, такими как find
или внутри bash for
или while
циклов, для переименования нескольких файлов.
В следующем примере показано, как использовать цикл Bash for для переименования всех .html
файлов в текущем каталоге, изменив .html
расширение на .php
.
for f in *.html; do
mv -- "$f" "${f%.html}.php"
done
Давайте проанализируем код построчно:
- Первая строка создает
for
цикл и перебирает список всех файлов, окантованных.html
. - Вторая строка применяется к каждому элементу списка и перемещает файл в новый, заменяя его
.html
на.php
. Часть${file%.html}
использует расширение параметра оболочки, чтобы удалить.html
часть из имени файла. done
указывает на конец сегмента цикла.
Вот пример использования mv
в сочетании с find
для достижения того же, что и выше:
find . -depth -name "*.html" -exec sh -c 'f="{}"; mv -- "$f" "${f%.html}.php"' ;
Команда find
передает все файлы, оканчивающиеся .html
в текущем каталоге, по mv
одному, используя -exec
опцию. Строка {}
— это имя файла, обрабатываемого в данный момент.
Как видно из приведенных выше примеров, переименование нескольких файлов с помощью mv
команды — непростая задача, поскольку требует хорошего знания сценариев Bash.
Переименование файлов с помощью rename
команды
Команда rename
используется для переименования нескольких файлов. Эта команда более сложна, чем mv
она требует базовых знаний о регулярных выражениях.
Существует две версии rename
команды с разным синтаксисом. В этом уроке мы будем использовать версию команды Perl rename
. Если у вас не установлена эта версия в вашей системе, вы можете легко установить ее, используя менеджер пакетов вашего дистрибутива.
-
Установить
rename
на Ubuntu и Debiansudo apt install rename
-
Установить
rename
на CentOS и Fedorasudo yum install prename
-
Установить
rename
на Arch Linuxyay perl-rename ## or yaourt -S perl-rename
Синтаксис rename
команды следующий:
rename [OPTIONS] perlexpr files
Команда rename
переименует в files
соответствии с указанным perlexpr
регулярным выражением. Вы можете прочитать больше о регулярных выражениях perl здесь .
Следующий пример изменит все файлы с расширением .html
на .php
:
rename 's/.html/.php/' *.html
Вы можете использовать -n
опцию для печати имен файлов, которые будут переименованы, без переименования их.
rename -n 's/.html/.php/' *.html
Вывод будет выглядеть примерно так:
rename(file-90.html, file-90.php)
rename(file-91.html, file-91.php)
rename(file-92.html, file-92.php)
rename(file-93.html, file-93.php)
rename(file-94.html, file-94.php)
По умолчанию rename
команда не перезаписывает существующие файлы. Передайте -f
опцию, чтобы разрешить перезаписывать существующие файлы:
rename -f 's/.html/.php/' *.html
Ниже приведены еще несколько распространенных примеров использования rename
команды:
-
Заменить пробелы в именах файлов подчеркиванием
rename 'y/ /_/' *
-
Преобразование имен файлов в нижний регистр
rename 'y/A-Z/a-z/' *
-
Преобразовать имена файлов в верхний регистр
rename 'y/a-z/A-Z/' *
Вывод
Мы показали вам , как использовать mv
и rename
команды для переименования файлов.
Конечно, есть другие команды для переименования файлов в Linux, такие как mmv
. Новые пользователи Linux, которых пугает командная строка, могут использовать инструменты пакетного переименования GUI, такие как Métamorphose .
Содержание
- How To Rename Files And Directories In Linux
- Table of contents
- Using the file manager
- “mv” command
- Renaming multiple files at once
- “find” command
- “rename” command
- Summary
- Rename directory in Linux with command line
- Rename directory linux with mv command
- Conclusion
- Leave a Reply Cancel reply
- Как переименовать папку Linux
- Как переименовать папку в Linux
- 1. Файловый менеджер
- 2. Команда mv
- 3. Команда rename
- 4. Скрипт Bash
- 5. Команда find
- 6. Утилита gio
- Выводы
- How to Rename a Directory in Linux
- How to Rename a Folder Through “mv” Command
- How to Rename a Folder Through “rename” Command
- Conclusion
- About the author
- Wardah Batool
- How to rename and move files and directories on Linux
- Overview
- Rename files on Linux
- Moving a file on Linux
- Moving and Renaming files on Linux
- Moving Multiple files on Linux
- Moving Directories on Linux
- Verbose Output Flag
- Do Not Overwrite Existing Files
- Do Not Prompt to Confirm Overwrites
How To Rename Files And Directories In Linux
Table of contents
The ability to change files and directories names is one of the primary skills that every Linux user needs. This article continues the Bash article series and shows how to use various ways like file manager, mv, and rename utilities in combination with finding and bash looping constructs. Improve your Linux skills in just 3 minutes!
Using the file manager
One of the easiest ways of renaming files and directories in Linux for new users is using Midnight Commander.
Midnight Commander – is a console-based file manager cloned from the famous Norton Commander. Midnight Commander interface
To install Midnight Commander under Ubuntu:
For CentOS/Fedora/RHEL, use a different package manager:
To launch Midnight Commander, execute mc command.
You need to use keyboard arrows to move the file selector. To switch between left and right screens, you need to use the Tab key. You may use your mouse too, but you’re limited to select only files, which are visible on the screen.
To rename the file or directory, move the cursor on top of it and press F6. If you forgot the exact key, use your mouse to select Move/Rename from the File menu. Renaming files using Midnight Commander (menu)
Next, let’s look at how we can rename the files and directories by using mv and rename commands.
“mv” command
The mv command helps you move or rename files and directories from the source to the destination location. The syntax for the command is the following:
The source and destination can be a file or directory.
To rename file1.txt to file2.txt using mv, execute the following command:
To change the name of folder1 directory to folder2, use the following command:
Renaming multiple files at once
The mv utility can rename only one file at a time, but you can use it with other commands to rename more than one file. These commands include find and Bash for and while loops.
For example, let’s imagine you need to change the file extension for a specific file type in a directory. In the following example, we rename all HTML files and change their extension from html to php.
Here’s the example folder structure:
Now, let’s use the following Bash for-loop construct inside the example directory:
Here we stepped into the example directory. Next, we executed the mv command in Bash for-loop (the command between for and done keywords).
Here’s the expected outcome:
“find” command
Using find utility is one of the most common ways to automate file and directory operations in Linux.
In the example below, we are using the find to achieve the same goal and change file extension.
The find utility finds all files ending on .html and uses the -exec argument to pass every found file name to the sh shell script written in one line.
In the sh script-line, we set the variable f with the value of the file name f=”<>”, then we’re executing familiar mv command. A semicolon is used to split the variable set command from the mv command.
“rename” command
In some cases, it is easier to use the rename command instead of mv. And you can use it with regular expressions without combining with other Linux commands.
Here’s the syntax for the rename command:
For example, let’s rename all .php files back to .html:
If you wish to print the names of the files that you have selected for renaming, you can use the following command:
Summary
In this article, you’ve learned how to change files and directories names in Linux using various ways. We hope, this article was helpful. If so, please, help us to spread it to the world.
Источник
Rename directory in Linux with command line
How to rename a directory in Linux? It’s also one of the most asked questions by Linux beginners.
It’s a very basic operations, if you’re using a graphical file manager like Dolphin or Nautilus. But that’s not always not possible.
So here’s how you can rename folder in linux with basic command line tools.
Rename directory linux with mv command
The mv command has many use, could be used to rename files or move them to different location.
Below the generic way to rename folder in linux with the mv,
Now some useful argument to use along with the mv command.
You also have to take care of proper path when you’re dealing with directories not located in the current working directory.
Example: Assume you’ve a directory under the Documents directory, you want to rename it to logos_new, but you’re currently at home(
Have a look at the animation on top for more details.
Conclusion
So, that’s all about how you can rename directory linux, it’s very simple with the mv command.
You just have to take care of proper permission and carefully use sudo when needed. You can learn more about mv command here.
That’s the third installment of the linux for beginners series, read the first two below.
If you’ve any question or suggestion, please feel to leave comments, also don’t forget to share this tutorial with your Linux loving friends.
Leave a Reply Cancel reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Источник
Как переименовать папку Linux
Переименовать папку в Linux не намного сложнее, чем переименовать файл. Вы можете сделать это в графическом интерфейсе или с в терминале с помощью нескольких команд. Как и для других задач в Linux для этой существует множество способов решения.
Можно переименовать не просто одну папку, а выбрать стразу несколько и настроить для них массовое переименование. Вы можете использовать команду mv, rename, а также утилиту find для массового переименования. Но сначала давайте поговорим о том как всё это сделать в файловом менеджере.
Как переименовать папку в Linux
1. Файловый менеджер
Затем просто введите новое имя:
После нажатия клавиши Enter папка будет переименована.
2. Команда mv
Команда mv предназначена для перемещения файлов в другое место, однако её можно без проблем использовать чтобы переименовать папку или файл не перемещая его никуда. По сути, если файл или папка перемещается в пределах одного раздела диска, то на самом деле они просто переименовываются, а физически остаются на том же месте. Синтаксис:
$ mv старое_имя новое_имя
Чтобы переименовать папку
/Музыка/Папка 1 в Папка 11 используйте:
Если в имени файлов есть пробелы, то путь к файлу следует взять в кавычки. После выполнения этой команды папка будет переименована:
Обратите внимание, что слеш в конце папки назначения писать нельзя, иначе, ваша папка будет перемещена в указанную папку, если такая существует.
3. Команда rename
Команду rename можно использовать аналогично mv, только она предназначена специально для переименования файлов и папок поэтому у неё есть несколько дополнительных возможностей. Синтаксис команды следующий:
$ rename регулярное_выражение файлы
Но прежде всего программу надо установить:
sudo apt install rename
Самый простой пример, давайте заменим слово «Папка» на «Dir» во всех папках:
Можно пойти ещё дальше и использовать регулярное выражение чтобы заменить большие буквы в названиях на маленькие:
4. Скрипт Bash
Для массового переименования папок можно использовать скрипт на Bash с циклом for, который будет перебирать все папки в директории и делать с ними то, что нужно. Вот сам скрипт:
Этот скрипт добавляет слово _new для всех папок в рабочей директории, в которой был он был запущен. Не забудьте дать скрипту права на выполнение перед тем, как будете его выполнять:
chmod ugo+x dir_rename.sh
5. Команда find
Массовое переименование папок можно настроить с помощью утилиты find. Она умеет искать файлы и папки, а затем выполнять к найденному указанную команду. Эту особенность программы можно использовать. Давайте для всех папок, в имени которых есть dir добавим слово _1. Рассмотрим пример:
Утилита ищет все папки, в имени которых есть слово Dir, затем добавляет с помощью mv к имени нужную нам последовательность символов, в данном случае единицу.
6. Утилита gio
Утилита gio позволяет выполнять те же действия что и с помощью обычных утилит mv или rename, однако вместо привычных путей, можно использовать пути GVFS. Например: smb://server/resource/file.txt. Для переименования папки можно использовать команду gio move или gio rename. Рассмотрим пример с move:
Переименование папки Linux выполняется аналогично тому, как это делается с помощью mv.
Выводы
В этой небольшой статье мы рассмотрели как переименовать папку Linux. Как видите, для этого существует множество способов и всё делается достаточно просто.
Источник
How to Rename a Directory in Linux
Even if you want to move, copy or rename a directory, it is quite handy to perform these functions with commands; you don’t need to install any specific tool.
In Linux distributions, everything is in the form of directories. So, it is good to keep all of them in a structured way. Sometimes, we need to create temporary folders to save data and later on, to keep them permanently, we have to rename those directories.
There are no traditional commands to rename a folder/directory; it can be done using several ways. We will discuss in this guide how to change the directory name using the “mv” command and “rename” command. It might shock you that this operation can be performed using the “mv” command. The “mv” command is not only used to move one directory to another; it is a multi-purpose command which helps to rename a directory as well.
So, let’s check how we can do use the “mv” command and “rename” command:
How to Rename a Folder Through “mv” Command
To rename a folder through the “mv” command is the simplest way you have ever seen.
Create a directory in the terminal named “temp”:
To move the “temp” directory, make another directory with the name “temp 2”:
You can see in the home directory, two directories with the given names are created:
Now, move the “temp” to the “temp2” directory using the “mv” command:
Open the “temp 2” directory to check if the “temp” directory is successfully moved:
After moving, use the “mv” command again to rename a “temp2” directory:
So, the temp2 directory has been renamed successfully to the “new_Dir” directory:
You can also confirm it using a terminal to active a “new_Dir” directory in it, and check if the “temp” directory (we created first and moved to temp2 folder is present in the “new_Dir” directory or not):
To activate a “new_Dir” folder in the terminal, use the “cd” command:
Now, to display the list of files present in the “new_Dir” folder, type the “ls” command:
How to Rename a Folder Through “rename” Command
The “rename” command is a built-in tool in most Linux distributions that helps to rename folders and directories. It uses regular expressions to perform functions.
If it is not present in your system. Use the following command:
The syntax used for the “rename” command is:
Consider the given examples to check if it’s working:
Example 1:
To rename the directories from lowercase to uppercase, run the ls command to display directories in the desktop directory:
Use the rename command with the following expressions to change letter case:
To confirm it, type “ls” again:
Example 2:
To rename the text files present in the desktop directory as pdf files, run the command:
Type the “ls” command to display the output:
You can also rename a directory through GUI by simply right click on the desired folder and navigate to the “rename” option:
Click on the “rename” option, type the name you want to update, and click to the “rename” button:
And the directory name will be changed:
Conclusion
In this write-up, we have seen how to rename a directory in Linux operating system. There are multiple ways to do it, but why choose a difficult way when the simplest approach is available.
We have learned from this guide to rename directories using the “mv” command and “rename” command. The “mv” command is considered a multi-tasking command tool whereas, using the “rename” command directories can be changed through regular expressions. We have also checked it through the GUI approach.
Wardah Batool
I am a Software Engineer Graduate and Self Motivated Linux writer. I also love to read latest Linux books. Moreover, in my free time, i love to read books on Personal development.
Источник
How to rename and move files and directories on Linux
Overview
In this tutorial, you will learn how to use the mv command to move and renames files and directories on Linux.
Files and directories on Linux as very similar, from a filesystem point of view. This means the operations done on one can be also done on the other, with very few exceptions.
As such, you will notice that commands used to perform actions on files are identical with directories.
Rename files on Linux
To rename a file in Linux you use the mv command. The command accepts two or more arguments. For renaming files, only two arguments are needed, which are the source file and the target file.
The mv command will take the source file specified and rename it to the target file.
To rename a file named student1 to student10, for example, you would run the following command.
Provided the file target is the same directory, all file attributes will remain, including permissions.
Moving a file on Linux
To move a file to another location we use the same method as renaming a file, except the file path should be different.
Moving and Renaming files on Linux
A file can be renamed during a move process using the mv command. You simply give the target path a different name. When mv moves the file, it will be given a new name.
Moving Multiple files on Linux
The mv command accepts multiple source files, which means we can move two or more files at the same time. When executing the mv command, each file listed will be considered a source with the last path being the exception. The last path will be treated as the target.
Moving Directories on Linux
Moving directories work the same as moving files. We specify the source directory and give a target directory.
For example, to move a directory path /tmp/logs to
/data/logs you would run the following command.
Moving Multiple Directories on Linux
As with files, multiple directories can be moved to a new location. We simply specially all of the directories to be moved, and then give a target directory for them to be moved to.
Verbose Output Flag
The mv command will perform its operations silently. No output will be printed to the screen while files or directories are being moved or renamed.
Do Not Overwrite Existing Files
In the example below, if the student2.txt file already exists, then the mv command will not rename the file and it will exit with an error.
Do Not Prompt to Confirm Overwrites
Источник