- Linux Rename Folder Command
- Linux Rename Folder Command
- How to rename folders in Linux
- How to move folders in Linux
- Getting help
- Unix Command To Rename A Folder
- Syntax to rename a directory on Unix
- Example: Unix rename a directory command
- Do not prompt for confirmation before overwriting
- Prompt for confirmation before overwriting
- How To Rename Directories and Folders In Linux?
- Rename Using Mv Command
- Verbose
- Overwrite Forcibly If Exists
- Prompt For Confirmation Before Overwriting
- Как переименовать папку Linux
- Как переименовать папку в Linux
- 1. Файловый менеджер
- 2. Команда mv
- 3. Команда rename
- 4. Скрипт Bash
- 5. Команда find
- 6. Утилита gio
- Выводы
- How to change directory in Linux using cd command
- How to change directory in Linux
- Changes the current directory in Linux
- How do I go back to my home folder or directory in Linux?
- How to change a folder in Linux
- Linux change directory and symbolic links
- Shell environment variables
- A note about the autocd option
- Autocorrect errors/typos of a folder name
Linux Rename Folder Command
Linux Rename Folder Command
The procedure to rename a folder or directory on Linux:
- Open the Terminal application.
- Type the following command to rename foo folder to bar:
mv foo bar
You can use full path too:
mv /home/vivek/oldfolder /home/vivek/newfolder
Let us see examples and syntax in details.
How to rename folders in Linux
The pwd command shows current working directory:
pwd
Sample outputs:
mv command syntax form is as follows:
mv old-name new-name
mv [options] old-name new-name
mv [options] source target
To rename a directory called pics to mypictures in the current directory:
pwd
ls -l
mv pics mypictures
Verify it with the ls command:
ls -l
If the mypictures folder is located in the same directory as the pics folder, then the pics folder can only be renamed. Hence always use pwd command and ls command to find out your current working directory.
How to move folders in Linux
The following command would move a folder named accounting, without changing its name, from the current directory to an existing directory named /mnt/backups/:
mv accounting /mnt/backups/
You can give full path too:
mv /home/vivek/accounting/ /mnt/backups/
Let us move multiple files/folders. The following mv command moves all files and directories, including all the contents of those directories, from the current directory to the directory /raid/home/new/vivek/:
mv * /raid/home/new/vivek/
The asterisk is a wildcard character that represents any or all files in the current directory. To get confirmation when renaming or moving folders pass the -i too mv command to avoid overwriting files/folders:
mv -i file.doc
/Documents/
OR
mv -i ExcelFiles
/Documents/
Sample outputs:
Pass the -v to explain what is being done i.e. show whether file being moved or renamed and so on:
$ mv -v old new
$ mv -v file.doc /backups/
Pass the -n option to mv to not overwrite an existing file/folder:
$ mv -v -n file.doc /backups/
Sample session from above commands:
Getting help
Issue the following command at the cli to read man page of mv for all option:
man mv
OR
mv —help
Sample outputs:
Источник
Unix Command To Rename A Folder
H ow do I rename a folder under UNIX operating systems using a command line tools?
You need to use the mv command to rename a folder under UNIX operating systems. You must have write permission for all folders.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | None |
Est. reading time | 1m |
Syntax to rename a directory on Unix
The syntax is as follows:
mv old-folder-name new-folder-name
mv /path/to/old /path/to/new
Example: Unix rename a directory command
In this example, a folder called drivers is renamed as olddrivers. Open a terminal (shell prompt) and type the following commands:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
OR pass the -v option to get verbose output:
Do not prompt for confirmation before overwriting
Prompt for confirmation before overwriting
Pass the -n option to mv command to do not overwrite an existing file/dirname. The -n option overrides any previous -f or -i options:
Recommend readings
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
How To Rename Directories and Folders In Linux?
Renaming or moving directories and folder can be tricky if those directories and folders have some subfolders. Or the destination may have all ready same name folder which will create some error. In this tutorial we will look how to rename and move directories and folders in Linux.
Rename Using Mv Command
The defacto command for rename directories and folders is mv . mv is the short form for the move . We can simply rename by providing the current directory and folder name and destination directory or folder name. Syntax is like below. If the source or current directory folder have content we need to rename by using recursive move. This will only change given directory or folder name but move all sub files and folder.
In this example we will rename directory named backup into old_backup .
Verbose
While renaming or moving files and folders we may need to get verbose information. Verbose mode will print every move or rename. This will be helpful for recursive option. We will provide -v to enable verbose.
Verbose
Overwrite Forcibly If Exists
In some cases there may be existing folder or directory with the new name. We need to confirm the overwrite. But this can be daunting task if there is a lot of them. We can overwrite existing files and folder with -f option automatically. -f means forcibly.
Prompt For Confirmation Before Overwriting
If we do not want to write existing file forcibly we can confirm for each file rename. In this case we have to use -i like below.
Источник
Как переименовать папку 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 «$
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 to change directory in Linux using cd command
I recently made the switch and started using Debian Linux. How do I change directory in Linux using the cd command? How can I change a directory or folder in Linux?
You need to use the cd command to move from your present directory to another directory. You must have execute or search permission in the specified directory. This page shows basic examples of how to change directory in Linux using the cd command.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | Bash with the terminal application |
Est. reading time | 2 minutes |
How to change directory in Linux
The procedure changes a directory or folder in Linux as follows:
- Let us change to your home directory in Linux, run: cd
- If you want to change to the /etc/security/ directory on Linux, execute: cd /etc/security/
- Want to go up one level of the directory tree in Linux? Try: cd ..
Let us see some examples and usage in details.
All examples tested with GNU/bash version 5.0.17 running on Ubuntu Linux 20.04 LTS desktop.
Changes the current directory in Linux
Let us change the current working directory to the home (login) directory in Linux, run:
cd
The default DIR is the value of the HOME shell variable. We can print that using the printf command/echo command as follows:
echo «$HOME»
To print the current working directory, use the pwd command:
pwd
Next change to an arbitrary directory named /etc/ufw/, type:
cd /etc/ufw
pwd
At this stage, you may want to list the directory contents. Hence, try the ls command:
ls
ls -l
Say you need to go down one level of the directory tree (say you want to change to the applications.d), run:
cd applications.d
pwd
ls -l
How do I go back to my home folder or directory in Linux?
Simply type any one of the following command:
cd
OR
cd
Changing to another directory in Linux using the cd command
How to change a folder in Linux
Get list of directories only in the current directory using the following:
ls -d */
Once you know the directory names, change it as per your needs:
cd linux
pwd
ls
To move back to a parent directory directory, type:
cd ..
Verify it:
pwd
ls
Linux change directory using the cd command
Linux change directory and symbolic links
One can force symbolic links to be followed. The syntax is:
cd -L dir1
cd -L link2
To use the physical directory structure without following symbolic links:
cd -P link2
Force symbolic links with the -L option and he physical directory structure with the -P option
Shell environment variables
- CDPATH : The search path for the cd command. It is a : separated list of pathnames that refer to directories. The cd utility shall use this list in its attempt to change the directory. An empty string in place of a directory pathname represents the current directory. If CDPATH is not set, it shall be treated as if it were an empty string. We can set it as follows:
export CDPATH=/home/vivek/projects
## another example ##
export CDPATH=/home/vivek/projects:/nfs:/efs
Now go to /home/vivek/projects/aws, I can simply type
cd aws
Insetad of
cd /home/vivek/projects/aws/
# OR #
cd
/projects/aws/
A note about the autocd option
If set, a command name that is the name of a directory is executed as if it were the argument to the cd command. This option is only used by interactive shells. Turn it on:
shopt -s autocd
Now type directory or folder names such as bin in the $HOME and it will automatically convert to “cd $HOME/bin”:
bin
Another example:
Downloads
Autocorrect errors/typos of a folder name
Suppose cdspell is set to on , minor errors in the spelling of a directory component in a cd command will be corrected. For example:
Источник