Renaming the file in linux

Linux Rename File Command

How to rename a file Linux?

The syntax is as follows:
mv old-file-name new-file-name
mv [options] old-file-name new-file-name
mv file1 file2

Examples: Renaming files with mv Command

In this example, rename a file called resumezzz.pdf to resume.pdf. Open a command-line terminal (select Applications > Accessories > Terminal), and then type:
mv resumezzz.pdf resume.pdf
If resumezzz.pdf is located in /home/vivek/docs/files directory, type:
cd /home/vivek/docs/files
mv resumezzz.pdf resume.pdf
OR
mv /home/vivek/docs/files/resumezzz.pdf /home/vivek/docs/files/resume.pdf
Use the ls command to view files:
ls -l file1
ls -l file1 file2
ls -l /home/vivek/docs/files/*.pdf
ls -l *.pdf

Linux rename a file syntax

In short, to rename a file:
mv file1 file2
You can get verbose output i.e. mv command can explain what is being done using the following syntax:
mv -v file1 file2
Sample outputs:

To make mv interactive pass the -i option. This option will prompt before overwriting file and recommended for new users:
mv -i file1 file2
Sample outputs:

How to use rename command to renames multiple files

The syntax is:
rename ‘s/old/new/’ files
rename [options] ‘s/old/new/’ files
For example, rename all perl files (*.perl) to *.pl, enter:
rename ‘s/perl/pl/’ *.perl
OR
rename -v ‘s/perl/pl/’ *.perl
Sample outputs:

The above command changed all files with the extension .perl to .pl. See “Howto Rename Multiple Files At a Shell Prompt In Linux or Unix” for more info.

  • 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

Detailed information about mv command

You can also view the manual page on mv using the following command:
man mv
OR
info mv
OR
man rename

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

Источник

How to Rename a File in Linux With Simple Command Line Options

Developed in the early 1990s, Linux has remained a popular operating system for both personal use and commercial servers. Today, there are over 600 Linux distributions (versions) available, though only a handful of them remain in common use. Based on Unix, the Linux system is prized for its portability, reliability, and stability. There are many individuals (primarily industry professionals) who prefer using Linux over any other operating system.

That said, Linux does require some advanced knowledge to use. While today most Linux distributions have a GUI (graphical user interface), many don’t. Working with Linux requires prior knowledge because most commands are given through a command-line text.

If you’ve worked in DOS or have programmed in C, you will know how to use a command line. But with Linux, it’s all about knowing individual commands — including the commands to rename and move files.

Today, we’re going to take a look at how to rename a file in Linux. We’ll look at the rename tools that Linux offers, renaming a single file, how to rename files and directories, and renaming multiple files through batch rename.

Last Updated September 2021

Linux Administration (Ubuntu and CentOS) for Beginners. Get the Linux skills to boost your career and get ahead. | By Andrei Dumitrescu, Crystal Mind Academy

How to rename a single file in Linux

If we need to rename a single file in Linux, we have two options: we can create a copy of the file with a new name (and delete the old one) or we can rename the file by moving it (with the MV command).

Renaming a file by copying and deleting it

Linux users copy a file by using the “cp” command. When you copy a file, you give the source files and rename the files.

Читайте также:  Скайрим для mac os последней версии

As an example, if we were to rename “august.png” to “september.png”:

This will create a copy of the file with a new name. But now you’ll have two copies. You’ll resolve this by deleting the old file. You delete with “rm.”

You may be wondering why this is so cumbersome compared to Windows, where you’d just rename a file. Linux has a lot of power, but it manages that power by putting it in the user’s hands. Linux users will perform more operations incrementally, but they have complete control over how those operations are performed.

This gives way to another issue: We could have named that second file september.jpg or september.doc. And then the file would no longer work! Linux provides a lot of power and a lot of freedom.

Renaming a file by moving it

You may be relieved to know that there is an easier method. But it’s a counterintuitive one. You can rename a file by “moving it” to a new file name.

This actually does what you would think of as a “rename” command and in a single step. But it should be noted that it’s also the general “move” command. So, you are moving the file at the same time. If you move it to a different directory, it will be moved as well as renamed.

As with the cp command, you have to be aware of file extensions. For example, say we introduced a typo and typed:

That action would break our file.

File extensions and renaming

For the most part, Windows protects you from changing the extension of a file. When you click a file in Windows to rename it, it only highlights the actual name, not the extension. You need to do a little work to change the extension of a file.

Linux doesn’t protect you. The extension is part of the file name and can be changed at any time. For that reason, you should be very aware of file extensions. .JPEG is not necessarily the same as .JPG, even if they both denote “JPG” files.

If a file is no longer working after you’ve moved, renamed, or copied it, it’s very likely that it’s because of an error with the file extension.

How to rename multiple files in Linux

What if you wanted to rename multiple files in Linux? This is where we start to see the advantages of using a command-line system.

Let’s say we did make a mistake. We changed everything to JPGs, but instead, they need to be PNGs. We can do this like so:

What this does is it uses a wildcard operator (*) to select any file that ends with JPG and changes that to a PNG. We had better know what we’re doing, though, because if there were any actual JPGs, they’re broken now.

Wildcards are one of the simplest forms of regular expressions. If we had wanted to rename the files in Windows, we would have had to click on them one by one. To rename the files in Linux, we can just use an expression to highlight them all. For that reason, power users in Linux can perform operations very quickly.

Renaming a directory in Linux

One of the quirks of Linux and Unix is that not much changes whether you’re using files or directories. A directory is more or less a blank file that contains other files. If we had a directory called “2021” and we wanted to rename it to “2022,” we would do this:

It’s as simple as that. Existing directories are treated like existing files that do not have a file extension by the MV command.

Rename a file while moving it in Linux

Earlier, we noted that we are using the MV command to rename files and that we could also move the file to a different directory if we so chose.

Now let’s say we want to rename august.png to september.png and also move it into the 2022 directory.

As again, both the directory and the file name (and its extension) are just pointers to where data is. This remains consistent throughout Linux.

Using flags (options) for your operations

Linux makes it possible to use something called “flags,” or options, with its commands. This controls how the command is performed.

Two commands you may want to know are -i and -v.

  • -i. This is the interactive option, and it makes it possible for you to “interrupt” the sequence to confirm actions.
  • -v. This is the verbose option, and it makes it possible for you to see everything that happens with the command as it happens.

Both of these option flags can be helpful when using the MV command in Linux.

Using the interactive renaming function in Linux

We’ve noted a couple of times that it’s possible to make large, potentially irrevocable mistakes in Linux. But there’s also a way to get around this. If you add the “-i” option with the MV command, you’ll be prompted before anything is done.

Читайте также:  Создание установщика для windows

Let’s say we type:

But the problem is, we’ve already created september.png. It already exists! The “interactive” function will let us know we’re about to overwrite an existing file. We can then type “Y” or “N” to either confirm the action or deny it.

If we knew that it was going to be overwritten anyway, we may be fine with it. But otherwise, we might want to know that there’s another file in danger.

Using the verbose option to track what’s happening

In addition to interactively interrupting your commands, you may also want to just know what operations are occurring. With Linux, you can always use the -v or -verbose option.

This will tell you exactly what it has done to the source files and the new files. And you can also:

This will tell you about all the operations and also allow you to interrupt them. Whenever you’re using a new command, consider using -v for verbose. The -v flag should work for nearly any command.

Mass moving and renaming files in Linux

Sometimes you need to move and rename a large number of files in Linux. Consider that you might have an entire directory of files that have to be either changed or moved. This could happen if you installed something into the wrong directory.

For this, Linux has another command altogether: MMV. MMV can be used to move, link, and append files. It’s a non-destructive method of doing so; it will try to identify any potential errors or collisions.

This is particularly valuable because you don’t want to accidentally ruin a lot of files at once.

The above would be another way of changing all PNGs to JPGs, in the event that for instance, a large number of files had the wrong extension. This could happen if you had copied the original file over incorrectly.

But you’ll notice that we could have done this with the MV command, too. The only difference is that MMV is a more careful way of doing this.

If you wanted to mass copy a lot of files, you could even copy over the entire directory:

And that would copy 2021 to 2022 while still leaving 2021. Copying is less dangerous than moving because copying doesn’t inherently delete the original files. Moving does. This is one reason why when renaming a file, we looked at the CP function before the MV function — there is less that can go wrong with the operation because it’s not inherently destructive.

Installing rename in Linux

At this point, you might be thinking “Why can’t I just rename?” Actually, you can. There is a “rename” command in Linux, but you would need to install it.

On your administrative account for Ubuntu or Debian:

For Fedora or CentOS:

(If you have a different distribution, look up your installation syntax.)

This will install the “rename” package. After you install rename, you’ll be able to use complex regular expressions to rename your files.

Complex regular expressions are a topic in and of themselves. We saw that * can be used as a wildcard. But with regular expressions, we can also select things like “any file that starts with letters but ends with numbers” or “any file that has 59 in it.” Regular expressions can be used to identify email addresses or other patterns — they are very powerful but take some practice.

The rename command will not operate much differently from MV, MVV, or even CP. The difference is that you’ll have a dedicated function called “rename” that you can use. There are many function packages for different Linux distributions that you can install. If you’re trying to complete an operation and you can’t find it in vanilla Linux, consider looking for a package.

Getting started with Linux

Linux has an internal manual ($ man) that can be used to look up commands. To look up more information about the move command in Linux, you can also always type in:

Or look up the $ man entries for anything else.

Linux requires a lot of memorization. For the most part, you just need to know what’s possible in the system. Once you know what’s possible, you should be able to reference the manual to figure out how.

But you should always remember that Linux does what it’s told — there are fewer safeguards with the Linux system. While Windows might alert you that you’re overwriting a file, Linux isn’t likely to alert you unless you specifically ask that it does. If you’re just learning Linux now, a great way to do so is through a Linux bootcamp or workshop. There are so many distributions of Linux, you’ll also want to decide which distribution you want to use first. Check out our guide to finding the best Linux distro!

Читайте также:  Навигатор waze для windows

Page Last Updated: September 2021

Источник

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

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

В этой статье мы рассмотрим как переименовать файл в Linux с помощью терминала, рассмотрим такие возможности, как массовое пакетное переименование файлов, а также регулярные выражения.

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

В Linux существует замечательная стандартная утилита mv, которая предназначена для перемещения файлов. Но по своей сути перемещение — это то же самое, что и переименование файла linux, если выполняется в одной папке. Давайте сначала рассмотрим синтаксис этой команды:

$ mv опции файл-источник файл-приемник

Теперь рассмотрим основные опции утилиты, которые могут вам понадобиться:

  • -f — заменять файл, если он уже существует;
  • -i — спрашивать, нужно ли заменять существующие файлы;
  • -n — не заменять существующие файлы;
  • -u — заменять файл только если он был изменен;
  • -v — вывести список обработанных файлов;

Чтобы переименовать файл linux достаточно вызвать утилиту без дополнительных опций. Просто передав ей имя нужного файла и новое имя:

mv file newfile

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

mv /home/sergiy/test/newfile /home/sergiy/test/file1

Обратите внимание, что у вас должны быть права на запись в ту папку, в которой вы собираетесь переименовывать файлы. Если папка принадлежит другому пользователю, возможно, нужно будет запускать программу через sudo. Но в таком случае лучше запускать с опцией -i, чтобы случайно ничего не удалить.

Переименование файлов Linux с помощью rename

В Linux есть еще одна команда, которая позволяет переименовать файл. Это rename. Она специально разработана для этой задачи, поэтому поддерживает такие вещи, как массовое переименование файлов linux и использование регулярных выражений. Синтаксис утилиты тоже сложнее:

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

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

В качестве старого имени указывается регулярное выражение или часть имени которую нужно изменить, новое имя указывает на что нужно заменить. Файлы — те, которые нужно обработать, для выбора файлов можно использовать символы подставки, такие как * или ?.

Рассмотрим опции утилиты:

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

Например, переименуем все htm файлы из текущей папки в .html:

rename ‘s\.htm/\.html/’ *.htm

Или для изображений:

Символ звездочки означает, что переименование файлов linux будет выполнено для всех файлов в папке. В регулярных выражениях могут применяться дополнительные модификаторы:

  • g (Global) — применять ко всем найденным вхождениям;
  • i (Case Censitive) — не учитывать регистр.

Модификаторы размещаются в конце регулярного выражения, перед закрывающей кавычкой. Перед тем, как использовать такую конструкцию, желательно ее проверить, чтобы убедиться, что вы не допустили нигде ошибок, тут на помощь приходит опция -n. Заменим все вхождения DSC на photo в именах наших фотографий:

rename -n ‘s/DSC/photo/gi’ *.jpeg

Будут обработаны DSC, DsC и даже dsc, все варианты. Поскольку использовалась опция -n, то утилита только выведет имена изображений, которые будут изменены.

Можно использовать не только обычную замену, но и полноценные регулярные выражения чтобы выполнить пакетное переименование файлов linux, например, переделаем все имена в нижний регистр:

Из этого примера мы видим, что даже если такой файл уже существует, то он перезаписан по умолчанию не будет. Не забывайте использовать опцию -n чтобы ничего случайно не повредить.

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

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

sudo apt install pyrenamer

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

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

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

Выводы

В этой статье мы рассмотрели как переименовать файл в консоли linux. Конечно, есть и другие способы, например, написать скрипт, или использовать файловые менеджеры. А как вы выполняете сложные операции по переименованию? Напишите в комментариях!

Источник

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