Команда переименования файла линукс

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

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

Утилита MV для переименования файла Linux

В системе Линукс есть стандартная команда «mv». Обычно она доступна по молчанию, используется для перемещения файлов, что при некоторых условностях одновременно является и их переименованием. Как выглядит синтаксическая структура команды:

  • -f – замена существующего файла.
  • -i – запрос на необходимость замены файлов.
  • -n – отказ от замены файлов.
  • -u – замена тех файлов, которые были видоизменены.
  • -v – демонстрация перечня обработанных файлов.

Итак, как переименовать файл Линукс при помощи стандартной программы? Для этого необходимо ввести в терминале название вспомогательной программы + текущее имя файла + новое название для файла.

Использование команды mv

Как видно из скриншота выше, команда mv переименовала файл «oldfile» в «newfile».

При необходимости переместить его из одного каталога в другой, это можно сделать с указанием полного пути например так:

$ mv /home/ya/oldfile /home/ya/newfile

Пример mv

Результат выполнения будет такой же.

Чтобы беспрепятственно переместить документ, нужно иметь права на запись в конкретный каталог. Что делать, если прав нет, и папка принадлежит иному юзеру системы?

Ответ: придется запускать утилиту через sudo или su.

ВАЖНО! при работе с чужими папками рекомендуется запускать утилиту mv с опцией -i. Таким образом, вы не сможете удалить информацию из папки – все данные останутся на месте, но уже с некоторыми коррективами.

Команда rename для переименования файла Linux

Для воплощения данной задумки в жизнь юзер системы может воспользоваться командой под названием «rename». Как и её аналоги, она тоже разработана для этих целей, но имеет за собой более обширный функционал. С её помощью легко выполнить массовое переименование документов Линукс. В отдельно взятых случаях это действительно необходимо.

Как выглядит синтаксическая структура команды:

rename опции старое_имя новое_имя файлы

Какие функции программы могут потребоваться пользователю Linux:

  • v – демонстрация перечня файлов, которые были обработаны.
  • n – запуск пробного режима (теста) для более подробного изучения специфики команды. Это означает, что заданные манипуляции не будут реализованы на практике.
  • -f – опция для принудительной перезаписи файлов, которые уже наличествуют в системе.
Читайте также:  Linux как установить время

И сразу же рассмотрим на примере. Допустим, нужно поменять название для всех txt файлов из каталога в .doc:

Примечание: наличие символа «*» в заданной команде подразумевает переименование всех файлов, которые содержатся в каталоге.

Утилита PYRENAMER для переименования файла

Некоторые пользователи Линукс не любят иметь дело с терминалом, и стараются находить альтернативные способы решения проблем, непосредственно связанных с системой. Если вы относитесь к числу таких людей, предлагаем вашему вниманию другой метод массового переименования файлов. Для реализации этой идеи вы можете воспользоваться графической утилитой pyrenamer. Это означает, что все действия можно выполнить при помощи мышки, но перед этим нужно установить программу:

Утилита представлена в виде окна, состоящего из нескольких блоков:

  • Перечень файлов, которые необходимо видоизменить;
  • Раздел настроек (здесь пользователь задает параметры переименования файлов);
  • Дерево файловой системы.

В утилите pyrenamer часто встречаются подсказки, что значительно упрощает и ускоряет работу пользователю Линукс. С помощью данной программы можно выполнить не только массовое переименование файлов, но и выборочное – вплоть до одного файла. Pyrenamer является полноценным аналогом команды rename и утилиты mv, не уступая им в своей функциональности. Это прекрасный инструмент для тех, кто хочет вносить нужные правки в графическом интерфейсе, не прибегая к использованию терминала и сложных команд.

Заключение

В данной статье представлены самые простые и доступные способы переименования файлов в Линукс (через терминал и графический интерфейс), которые помогут новичку освоить свой дистрибутив.

Источник

How to Rename Files in Linux

Linux provides several options for renaming files, including using the GUI and multiple dedicated terminal commands. This makes it relatively easy to rename individual files, but it can be challenging to rename multiple files at once.

In this tutorial, we will go over different commands you can use in the Linux terminal to rename files in Linux.

How to rename files 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

Rename Files with the mv Command

The Linux mv (move) command is used to move files and directories from the terminal. It uses the following syntax:

mv [options] [source] [destination]

If you specify a directory as the destination when using the mv command, the source file moves to that directory. If the destination is another file name, the mv command renames the source file to that name instead.

Note: Learn more about using the mv command in our guide to moving directories in Linux.

Rename a Single File with the mv Command

Using the mv command with its default syntax allows you to rename a single file:

mv [options] [current file name] [new file name]

For example, if we want to rename example1.txt into example2.txt, we would use:

mv example1.txt example2.txt

Since there is no output if the command is successful, we are using the ls command to check if the name is changed:

Читайте также:  Kali linux light 32 bit iso

Renaming a single file using the mv command

Rename Multiple Files with the mv Command

On its own, the mv command renames a single file. However, combining it with other commands allows you to rename multiple files at the same time.

One method is to use the find command to select multiple files with a similar name, then use the mv command to rename them:

find . -depth -name "[current file name element]" -exec sh -c 'f="<>"; mv -- "$f" "$[new file name element]"' \;

Using this syntax, the find command defines an element of the current file name as the search parameter. Next, -exec executes the mv command on any files that match the search, changing their current filenames to the new one.

For instance, if we have example1.txt, example2.txt, and example3.txt and want to change the extension to .pdf:

find . -depth -name "*.txt" -exec sh -c 'f="<>"; mv -- "$f" "$.pdf"' \;

Renaming multiple files using the find and mv commands

Another method is to use the mv command as a part of a for loop in a bash script.

Using the same example, start by creating and opening a bash script file using a text editor such as Nano:

Add the following lines to the script:

#!/bin/bash for f in *.txt; do mv -- "$f" "$.pdf" done 
  • The first line instructs the script to search for all the files in the current directory ending with .txt.
  • The second line uses the mv command on each file found to replace the .txt extension with .pdf.
  • The third line ends the loop segment.

Press Ctrl+X, then type Y and press Enter to save the changes to the script and exit.

Use the sh command to execute the script:

Renaming multiple files using a bash script

Note: Learn how to compare two files using the diff command.

Rename File with the rename Command

The rename command is used to rename multiple files or directories in Linux. It offers more features than the mv command but can be more challenging to use since it requires basic knowledge of Perl expressions.

How to Install the rename Command

On many Linux distributions, the rename command is not available 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

rename Command Syntax and Options

There are three types of Perl regular expressions: match, substitute and translate. The rename command uses substitute and translate expressions to change file and directory names.

Substitute expressions replace a part of the filename with a different string. They use the following syntax:

rename [options] 's/[filename element]/[replacement]/' [filename]

With this syntax, the command renames the file by replacing the first occurrence of the filename element with the replacement. In the command above:

  • rename : Invokes the rename command.
  • [options] : Provides an optional argument that changes the way the command executes.
  • s : Indicates a substitute expression.
  • [filename element] : Specifies the part of the filename you want to replace.
  • [replacement] : Specifies a replacement for the part of the current filename.
  • [filename] : Defines the file you want to rename.

A translate expression translates one string of characters into another, character for character. This type of expression uses the following syntax:

rename [options] 'y/[string 1]/[string 2]/' [filename]

An example of a rename command using a translate expression:

In this example, every a character in the filename is replaced by an x, every b by a y, and every c by a z.

The rename command uses the following options:

  • -a : Replaces all the occurrences of the filename element instead of just the first one.
  • -f : Forces an overwrite of existing files.
  • -h : Displays the help text.
  • -i : Displays a prompt before overwriting existing files.
  • -l : Replaces the last occurrence of the filename element instead of the first one.
  • -n : Performs a dry run, making no permanent changes. Best combined with the verbose output ( -v ).
  • -s : Renames the target instead of the symlink.
  • -v : Shows a verbose version of the output.
  • -V : Displays the command version.

rename Command Examples

1. Change File Extension

Returning to our last example, to change the file extension from .txt to .pdf, use:

Using the rename command to replace the file extension

2. Replacing a Part of a Filename

Replacing a different part of the filename follows the same syntax. To rename example1.txt, example2.txt, and example3.txt to test1.txt, test2.txt, and text3.txt, use:

rename -v 's/example/test/' *.txt

Renaming multiple files using the rename command

3. Delete a Part of a Filename

The rename option also allows you to delete a part of the filename by omitting the replacement part of the expression. For instance, if we want to shorten example into ex:

Removing a part of the file name using the rename command

4. Rename Files with Similar Names

Another use for the rename option is to rename files with similar names. For instance, if we want to rename files with example and sample in their name to test:

rename -v 's/(ex|s)ample/test/' *.txt

Renaming multiple files with similar names using the rename command

5. Rename Files Character-by-Character

The rename command also allows you to use translate expressions to rename files on a character-by-character basis. For instance, if you want to rename multiple files named example file by replacing the blank space with an underscore (_):

Removing blank spaces from file names using the rename command

6. Convert Lowercase Characters

To convert lowercase characters in filenames into uppercase characters, use:

Converting file names from lowercase to uppercase using the rename command

7. Convert Uppercase Characters

The reverse also works if we switch the order of the uppercase and lowercase characters in the expression:

Converting file names from uppercase to lowercase using the rename command

Note: Be careful when changing the character case, as this also changes the file extension.

After reading this tutorial, you should be able to rename files using the mv and rename commands in Linux.

Learn more about using Linux commands in our Linux Commands Cheat Sheet.

Источник

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