Change directory name linux

Содержание
  1. Как переименовать каталоги в Linux
  2. Переименование каталогов
  3. Переименование нескольких каталогов
  4. Переименование нескольких каталогов с помощью mv
  5. Переименование нескольких каталогов с rename
  6. Выводы
  7. Unix Command To Rename A Folder
  8. Syntax to rename a directory on Unix
  9. Example: Unix rename a directory command
  10. Do not prompt for confirmation before overwriting
  11. Prompt for confirmation before overwriting
  12. How to change directory in Linux using cd command
  13. How to change directory in Linux
  14. Changes the current directory in Linux
  15. How do I go back to my home folder or directory in Linux?
  16. How to change a folder in Linux
  17. Linux change directory and symbolic links
  18. Shell environment variables
  19. A note about the autocd option
  20. Autocorrect errors/typos of a folder name
  21. Linux Rename Folder Command
  22. Linux Rename Folder Command
  23. How to rename folders in Linux
  24. How to move folders in Linux
  25. Getting help
  26. How to change directory in Linux terminal
  27. How to change directory in Linux terminal
  28. How to use the Linux command line to change directory or folder
  29. How to print the current working directory in Linux
  30. cd command in Linux termianl
  31. Absolute vs Relative pathname
  32. Understanding . and .. directories
  33. How can I return directly to my home directory when using the Linux terminal?
  34. How do I change directories in the Linux terminal and return to the previous directory?
  35. A note about symbolic links and cd command
  36. Linux cd command cheat sheet
  37. Conclusion

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

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

В этой статье объясняется, как переименовывать каталоги с помощью командной строки.

Переименование каталогов

В Linux и Unix-подобных операционных системах вы можете использовать команду mv (сокращение от move) для переименования или перемещения файлов и каталогов из одного места в другое.

Синтаксис команды mv для перемещения каталогов следующий:

Например, чтобы переименовать каталог dir1 в dir2 вы должны запустить:

При переименовании каталогов вы должны указать ровно два аргумента для команды mv . Первый аргумент — это текущее имя каталога, а второй — новое имя.

Важно отметить, что если dir2 уже существует, dir1 перемещается в каталог dir2 .

Чтобы переименовать каталог, которого нет в текущем рабочем каталоге, необходимо указать абсолютный или относительный путь:

Переименование нескольких каталогов

Переименование одного каталога — простая задача, но переименование сразу нескольких каталогов может быть проблемой, особенно для новых пользователей Linux.

Одновременное переименование нескольких каталогов требуется редко.

Переименование нескольких каталогов с помощью mv

Команда mv может переименовывать только один файл за раз. Однако его можно использовать в сочетании с другими командами, такими как find или внутренние циклы, для одновременного переименования нескольких файлов.

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

Давайте проанализируем код построчно:

  • Первая строка создает цикл и выполняет итерацию по списку всех файлов.
  • Вторая строка проверяет, является ли файл каталогом.
  • Третья строка добавляет текущую дату в каждый каталог.

Вот решение той же задачи с использованием mv в сочетании с find :

Команда find передает все каталоги в mv один за другим с помощью параметра -exec . Строка <> — это имя обрабатываемого в данный момент каталога.

Как вы можете видеть из примеров, переименование нескольких каталогов с помощью mv — непростая задача, поскольку для этого требуется хорошее знание сценариев Bash.

Переименование нескольких каталогов с rename

Команда rename используется для переименования нескольких файлов и каталогов. Эта команда более сложна, чем mv поскольку требует базовых знаний регулярных выражений.

Есть две версии команды rename с разным синтаксисом. Мы будем использовать Perl-версию команды rename . Файлы переименовываются в соответствии с заданным регулярным выражением Perl .

В следующем примере показано, как заменить пробелы в именах всех каталогов в текущем рабочем каталоге символами подчеркивания:

На всякий случай передайте параметр -n для rename чтобы выводить имена переименовываемых каталогов без их переименования.

Вот еще один пример, показывающий, как преобразовать имена каталогов в нижний регистр:

Выводы

Мы показали вам, как использовать команды mv для переименования каталогов.

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Читайте также:  Как запустить windows с контрольной точки

Источник

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 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:

  1. Let us change to your home directory in Linux, run: cd
  2. If you want to change to the /etc/security/ directory on Linux, execute: cd /etc/security/
  3. 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

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

  1. 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/

  • HOME : The name of the directory, used when no directory operand is specified.
  • OLDPWD : The previous working directory as set by the cd command.
  • PWD : The current working directory as set by the cd command.
  • 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:

    Источник

    Linux Rename Folder Command

    Linux Rename Folder Command

    The procedure to rename a folder or directory on Linux:

    1. Open the Terminal application.
    2. 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:

    Источник

    How to change directory in Linux terminal

    M y Dell Laptop came preinstalled with Ubuntu Linux, and I am a new Linux desktop user. How do I change directories in the Linux terminal?

    Introduction – On Linux the cd command allows you to change directories when using the terminal application. This page shows how to change directory in Linux terminal using the cd command.

    Tutorial details
    Difficulty level Easy
    Root privileges No
    Requirements Linux terminal
    Est. reading time 3 minutes

    How to change directory in Linux terminal

    1. To return to the home directory immediately, use cd

    OR cd

  • To change into the root directory of Linux file system, use cd / .
  • To go into the root user directory, run cd /root/ as root user.
  • To navigate up one directory level up, use cd ..
  • To go back to the previous directory, use cd —
  • Let us see all examples and usage for terminal in details.

    How to use the Linux command line to change directory or folder

    The directory in which the user is currently working is called the current working directory (CDW).

    How to print the current working directory in Linux

    To display the name of the current/working directory, type the following pwd command:
    pwd

    cd command in Linux termianl

    The syntax is:
    cd
    cd ..
    cd /path/to/dir
    When cd command used without stipulating any directory name, cd command returns to the home directory. Let us change the directory to /usr/sbin/, run:
    cd /usr/sbin/
    Verify it:
    pwd
    Want to list the files in the /usb/sbin/ directory? Try the ls command:
    ls
    ls -l
    Let us go back to user’s home directory, run:
    cd
    Again verify it:
    pwd

    • 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

    Absolute vs Relative pathname

    The cd command changes the current directory when a directory name provided by the user. The name can be written as an absolute pathname (e.g. cd /etc/httpd/ ) or as local pathname relative to the root directory (e.g. cd conf.d/ ). For example:
    cd /etc/httpd/
    pwd
    ls
    cd conf.d/
    pwd
    ls

    The absolute vs. relative pathname for cd command in Linux

    Understanding . and .. directories

    On Linux the current directory is represented by a single dot ( . ) and two consecutive dots represent its parent directory ( .. ). Thus, to change to the parent of the current directory, run cd . .. For example:
    ls
    pwd
    cd ..
    pwd
    ls

    How can I return directly to my home directory when using the Linux terminal?

    How do I change directories in the Linux terminal and return to the previous directory?

    Simply pass the — option to the cd:
    cd —
    Verify it:
    pwd

    The -P option instructs cd to use the physical directory structure instead of following symbolic links:
    cd -P LinkDir
    pwd
    The -L option forces cd to follow symbolic links:
    cd -L LinkDir
    pwd

    Linux cd command cheat sheet

    Table 1: cd command under Linux
    Command Description
    cd Returns you to your login directory
    cd

    Also returns you to your login directory cd — Returns you to your previous working directory cd / Takes you to the entire system’s root directory. cd /root Takes you to the home directory of the root user. You must be the root user to access this directory. cd /home Takes you to the home directory, where user login directories are usually stored cd .. Takes you to the directory one level up. cd

    tom Takes you to tom’s home directory, if tom user has granted you permission cd /path/to/dir/ Take you to the /path/to/dir/ directory cd dir* Use a wildcard to change the directory name

    Conclusion

    The cd command is used to change the current directory in both Linux and other Unix-like systems. See Cd command wiki page.

    🐧 Get the latest tutorials on Linux, Open Source & DevOps via

    Источник

    Читайте также:  Система драйверов mac os
    Оцените статью