Linux поменять название файла

Rename a file or folder

As with other file managers, you can use Files to change the name of a file or folder.

To rename a file or folder:

  1. Right-click on the item and select Rename , or select the file and press F2 .
  2. Type the new name and press Enter or click Rename .

You can also rename a file from the properties window.

When you rename a file, only the first part of the name of the file is selected, not the file extension (the part after the last . ). The extension normally denotes what type of file it is (for example, file.pdf is a PDF document), and you usually do not want to change that. If you need to change the extension as well, select the entire file name and change it.

If you renamed the wrong file, or named your file improperly, you can undo the rename. To revert the action, immediately click the menu button in the toolbar and select Undo Rename , or press Ctrl + Z , to restore the former name.

Valid characters for file names

You can use any character except the / (slash) character in file names. Some devices, however, use a file system that has more restrictions on file names. Therefore, it is a best practice to avoid the following characters in your file names: | , \ , ? , * , < , " , : , >, / .

If you name a file with a . as the first character, the file will be hidden when you attempt to view it in the file manager.

Common problems

You cannot have two files or folders with the same name in the same folder. If you try to rename a file to a name that already exists in the folder you are working in, the file manager will not allow it.

File and folder names are case sensitive, so the file name File.txt is not the same as FILE.txt . Using different file names like this is allowed, though it is not recommended.

Читайте также:  Intellij idea ярлык linux

The file name is too long

On some file systems, file names can have no more than 255 characters in their names. This 255 character limit includes both the file name and the path to the file (for example, /home/wanda/Documents/work/business-proposals/… ), so you should avoid long file and folder names where possible.

The option to rename is grayed out

If Rename is grayed out, you do not have permission to rename the file. You should use caution with renaming such files, as renaming some protected files may cause your system to become unstable. See Set file permissions for more information.

More Information

You can choose the displayed language by adding a language suffix to the web address so it ends with e.g. .html.en or .html.de.
If the web address has no language suffix, the preferred language specified in your web browser’s settings is used. For your convenience:
[ Change to English Language | Change to Browser’s Preferred Language ]

The material in this document is available under a free license, see Legal for details.
For information on contributing see the Ubuntu Documentation Team wiki page. To report errors in this documentation, file a bug.

Источник

Переименование файлов в Linux

mv rename linux

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

Переименование командой mv

Команда mv (от слова move) используется для переименования или перемещения файлов и директорий из командной строки.

Синтаксис команды mv очень простой:

источник — файл(ы) или директория, которую необходимо переместить или переименовать.
назначение — файл или директория, в которую будет перемещен источник .

Основные опции:
-f — перезаписывать существующие файлы.
-n — не перезаписывать существующие файлы.
-i — выдавать запрос на перезапись существующих файлов.
-u — не перемещать файлы, которые уже существуют, если существующие файлы новее (время модификации новее).
-v — выводить имя каждого файла перед его переносом.

Как задавать имена файлов и директорий для переименования:

  • Чтобы переименовать файл с помощью команды mv нужно в качестве источника задать данный файл, а в качестве назначения указать новое имя файла.
  • Если указывается путь до файла, то директории должны совпадать, иначе файл будет перемещен в другую директорию.
  • Если в качестве источника указать файл, а в качестве назначения путь до файла в другой директории и задать новое имя файла, то файл будет перемещен в другую директорию и переименован.
  • Если в качестве источника указана директория, а в качестве назначения задано новое имя для данной директории, то директория будет просто переименована. Если же директория назначения уже существует, то директория источник будет перемещена в директорию назначения .
Читайте также:  Linux and microsoft windows

Переименование файла

Переименование файла 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

старое_имя — регулярное выражение или часть имени файла, которое нужно заменить на новое_имя .
новое_имя — задает результирующее имя файла (может быть регулярным выражением).

Основные опции:
-f — перезаписывать существующие файлы.
-n — вывести список файлов, которые будут переименованы и их новые имена, но не выполнять переименование.
-v — вывести список обработанных файлов.

Проще всего понять, как пользоваться данной командой, на примерах.

Изменение расширения файлов

Массово изменить расширение .html на .php у всех html-файлов.

По умолчанию rename не перезаписывает существующие файлы. Чтобы существующие файлы перезаписывались, используется опция -f :

Замена пробелов на подчеркивание

Заменить все символы пробелов в имени файлов на символ подчеркивания:

Конвертация имен файлов в строчные буквы

Конвертация имен файлов в прописные буквы

Показать, что именно будет переименовано, но не переименовывать

Чтобы избежать ошибок при переименовании файлов, особенно при использовании сложных регулярных выражений, можно сначала вывести список того, что будет переименовано, но не запускать само переименование. Для этого служит опция -n .

Например, мы хотим изменить расширение у файлов с .jpeg на .jpg . Используем опцию -n , чтобы просто вывести какие файлы будут переименованы:

Полное описание команд mv и rename можно получить, выполнив в терминале команды:

Массовое переименование с использованием программ

Для массового переименования файлов можно воспользоваться программами:

Источник

Rename a File in Linux – Bash Terminal Command

Zaira Hira

Zaira Hira

Rename a File in Linux – Bash Terminal Command

Renaming files is a very common operation whether you are using the command line or the GUI.

Читайте также:  Adobe master collection linux

Compared to the GUI (or Graphical User Interface), the CLI is especially powerful. This is in part because you can rename files in bulk or even schedule the scripts to rename files at a certain point in time.

In this tutorial, you will see how you can rename files in the Linux command line using the built-in mv command.

How to Use the Linux mv Command

You can use the built-in Linux command mv to rename files.

The mv command follows this syntax:

mv [options] source_file destination_file

Here are some of the options that can come in handy with the mv command:

  • -v , —verbose : Explains what is being done.
  • -i , —interactive : Prompts before renaming the file.

Let’s say you want to rename index.html to web_page.html . You use the mv command as follows:

zaira@Zaira:~/rename-files$ mv index.html web_page.html 

Let’s list the files and see if the file has been renamed:

zaira@Zaira:~/rename-files$ ls web_page.html

How to Name Files in Bulk Using mv

Let’s discuss a script where you can rename files in a bulk using a loop and the mv command.

Here we have a list of files with the extension .js .

zaira@Zaira:~/rename-files$ ls -lrt total 0 -rw-r--r-- 1 zaira zaira 0 Sep 30 00:24 index.js -rw-r--r-- 1 zaira zaira 0 Sep 30 00:24 config.js -rw-r--r-- 1 zaira zaira 0 Sep 30 00:24 blog.js

Next, you want to convert them to .html .

You can use the command below to rename all the files in the folder:

for f in *.js; do mv -- "$f" "$.html"; done

Let’s break down this long string to see what’s happening under the hood:

  • The first part [ for f in *.js ] tells the for loop to process each “.js” file in the directory.
  • The next part [ do mv — «$f» «$.html ] specifies what the processing will do. It is using mv to rename each file. The new file is going to be named with the original file’s name excluding the .js part. A new extension of .html will be appended instead.
  • The last part [ done ] simply ends the loop once all the files have been processed.
zaira@Zaira:~/rename-files$ ls -lrt total 0 -rw-r--r-- 1 zaira zaira 0 Sep 30 00:24 index.html -rw-r--r-- 1 zaira zaira 0 Sep 30 00:24 config.html -rw-r--r-- 1 zaira zaira 0 Sep 30 00:24 blog.html

Conclusion

As you can see, renaming files is quite easy using the CLI. It can be really powerful when deployed in a script.

What’s your favorite thing you learned here? Let me know on Twitter!

You can read my other posts here.

Источник

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