Linux group file rename

6 способов переименования нескольких файлов сразу в Linux

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

Но команда mv не будет поддерживать переименование нескольких файлов одновременно.

Она может переименовывать только один файл за раз.

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

В этом уроке мы научимся переименовывать несколько файлов одновременно в шести разных методах.

Все примеры, представленные здесь, тестируются в Ubuntu 18.04 LTS, однако они должны работать на любых операционных системах Linux.

Переименование нескольких файлов сразу в Linux

Может быть много команд и утилит для переименования группы файлов.

Я буду продолжать обновлять список, если буду сталкиваться с любым методом в будущем.

Метод 1 – Использование mmv

Утилита mmv используется для перемещения, копирования, добавления и переименования файлов в массовом порядке с использованием стандартных подстановочных знаков в Unix-подобных операционных системах.

Она доступна в репозиториях по умолчанию систем на базе Debian.

Чтобы установить его на Debian, Ubuntu, Linux Mint, выполните следующую команду:

Скажем, у вас есть следующие файлы в вашем текущем каталоге.

Теперь вы захотите переименовать все файлы, начинающиеся с буквы «a» на «b».

Конечно, вы можете сделать это вручную через несколько секунд.

Но подумайте, есть ли у вас сотни файлов и хотите их все переименовать?

Это довольно трудоемкий процесс. Здесь команда mmv приходит в помощь.

Чтобы переименовать все файлы, начиная с буквы «a» до «b», просто запустите:

Давайте проверим, были ли файлы переименованы или нет.

Как вы можете видеть, все файлы начинаются с буквы «a» (т.е. a1.txt, a2.txt, a3.txt), переименовываются в b1.txt, b2.txt, b3.txt.

Вы даже можете переименовать все файлы с определенным расширением на другое расширение.

Например, чтобы переименовать все .txt-файлы в формат .doc в текущем каталоге, просто запустите:

Вот еще один пример. Скажем, у вас есть следующие файлы.

Вы хотите заменить первое abc на xyz во всех файлах в текущем каталоге. Как бы вы поступили?

Обратите внимание, что в приведенном выше примере я включил шаблоны в одинарные кавычки.

Давайте проверим, действительно ли «abc» заменено на «xyz» или нет.

Файлы abcd1.txt, abcd2.txt и abcd3.txt были переименованы в xyzd1.txt, xyzd2.txt и xyzd3.txt.

Еще одна заметная особенность команды mmv – вы можете просто посмотреть вывод вместо переименования файлов с помощью опции -n, как показано ниже.

Таким образом, вы можете просто проверить, что действительно сделала команда mmv, прежде чем переименовывать файлы.

Для получения дополнительной информации см. Справочные страницы.

Способ 2. Использование утилиты rename

Утилита rename переименовывает данные файлы, заменяя первое выражение в их имени заменой.

Команда rename устанавливается в большинстве Unix-подобных операционных систем.

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

Например, у меня есть следующие файлы в текущем каталоге.

Заменим первое abc на xyz, где бы оно ни находилось. Для этого запустите:

Теперь проверьте, были ли сделаны изменения с помощью команды ls.

Иногда вы можете просто вывести выходные данные вместо переименования файлов.

Если это так, используйте флаг -n для отображения тех переименований, которые будут выполняться без их выполнения:

Читайте также:  Оптимизация батареи для windows

Как вы можете видеть, приведенная выше команда не вносила никаких изменений, а просто отображает имена переименованных файлов.

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

Если вы не хотите перезаписывать файлы, вы можете просто преобразовать их в заглавные или строчные буквы (и наоборот), чтобы предотвратить «уже существующие» ошибки.

Чтобы преобразовать все имена файлов в нижний регистр:

Давайте проверим, были ли внесены изменения.

Да, буквы в именах файлов были изменены с нижнего регистра на верхний регистр.

Аналогично, чтобы преобразовать имена файлов в нижний регистр, выполните:

Мы также можем удалить все пустые ячейки в имени файла.

Например, у меня есть следующий файл.

Чтобы удалить все пробелы в указанном выше имени файла, запустите:

Теперь имя файла не имеет пробелов.

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

Возможно, вы захотите изменить расширение файла, но не переименовать имена файлов.

Это также возможно.

Следующая команда переименовала бы все * .txt-файлы в * .doc.

Проверьте изменения с помощью команды ls:

Чтобы удалить расширение во всех файлах, соответствующих .txt, запустите:

Для получения дополнительной информации см. Справочные страницы.

Источник

Linux group file rename

Итак, у нас есть куча файлов, среди которых надо навести порядок. Для этого сделаем групповое переименование.

Rename

Утилита rename входит в стандартную поставку Debian, так что начнем с нее.

rename [ -v ] [ -n ] [ -f ] perlexpr [ files ]

-v отобразить имена успешно переименованных файлов.

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

-f перезаписать уже существующие файлы.

perlexpr — шаблон для переименования.

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

# rename ‘s/.sh/.sh.bak/g’ *.sh

Рассмотрим perlexr подробнее:

s=указывает, что требуется замещение.

/.sh/=Строка, которую будем замещать.

/.sh.bak/ = строка, на которую будем замещать

g=global, будем замещать все найденные вхождения.

С помощью rename можно быстро изменить регистр файлов. Например поднимем регистр файлов из примера:

MMV

mmv — программа для массового перемещения, переименования, копирования, объединения файлов.

По умолчанию она не включена в состав Debian. Поставим ее:

# apt-get install mmv

Наша задача решается одной строкой:

MV

Теперь решим нашу задачу стандартной командой mv. Для этого нам прийдется немного попрограммировать в bash.

for i in *.sh;
do mv $i `basename $i sh`sh.bak;
done

Попробуем усложить задачу. Например у нас есть куча файлов JPG:

1234234.jpg
e456567657.jpg
234df34.jpg

Мы хотим привести их к следующему виду:

file1.jpg
file2.jpg
file3.jpg

j=0;
for i in *.jpg;
do let j+=1;
mv $i file$j.jpg ;
done

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

1. Через + выбираем файлы по маске *.sh

2. Нажимаем F6 и в destination указываем *.sh.bak

Все примеры, приведенные выше, так или иначе работают во всех Linux, BSD, Mac OS, если стоят соответствующие утилиты.

Источник

How to rename a group of files on Linux

To rename a group of files with a single command, use the rename command. It requires the use of regular expressions and can tell you what changes will be made before making them.

For decades, Linux users have been renaming files with the mv command. It’s easy, and the command does just what you expect. Yet sometimes you need to rename a large group of files. When that is the case, the rename command can make the task a lot easier. It just requires a little finesse with regular expressions.

Unlike the mv command, rename isn’t going to allow you to simply specify the old and new names. Instead, it uses a regular expression like those you’d use with Perl. In the example below, the «s» specifies that we’re substituting the second string (old) for the first, thus changing this.new to this.old.

A change as simple as that would be easier using mv this.new this.old, but change the literal string “this” to the wild card “*” and you would rename all of your *.new files to *.old files with a single command:

As you might expect, the rename command isn’t restricted to changing file extensions. If you needed to change files named “report.*” to “review.*”, you could manage that with a command like this:

The strings supplied in the regular expressions can make changes to any portion of a file name — whether file names or extensions.

If you add the -v option to a rename command, the command will provide some feedback so that you can see the changes you made, maybe including any you didn’t intend — making it easier to notice and revert changes as needed.

On the other hand, using the -n (or —nono) option makes the rename command tell you the changes that it would make without actually making them. This can save you from making changes you may not be intending to make and then having to revert those changes.

If you’re then happy with those changes, you can then run the command without the -n option to make the file name changes.

Notice, however, that the “.” within the regular expressions will not be treated as a period, but as a wild card that will match any character. Some of the changes in the examples above and below are likely not what was intended by the person typing the command.

To ensure that a period is taken literally, put a backslash in front of it. This will keep it from being interpreted as a wild card and matching any character. Notice that only the “.old” files are selected when this change is made.

A command like the one below would change all uppercase letters in file names to lowercase except that the -n option is being used to make sure we review the changes that would be made before we run the command to make the changes. Notice the use of the “y” in the regular expression; it’s required for making the case changes.

In the example above, we’re changing all uppercase letters to lowercase, but only in file names that begin with an uppercase W.

Wrap-up

The rename command is very helpful when you need to rename a lot of files. Just be careful not to make more changes than you intended. Keep in mind that the -n (or spelled out as —nono) option can help you avoid time-consuming mistakes.

Sandra Henry-Stocker has been administering Unix systems for more than 30 years. She describes herself as «USL» (Unix as a second language) but remembers enough English to write books and buy groceries. She lives in the mountains in Virginia where, when not working with or writing about Unix, she’s chasing the bears away from her bird feeders.

Источник

Rename – A Command Line Tool For Renaming Multiple Files in Linux

We often use “mv” command to rename a single file in Linux. However, renaming multiple or group of files quickly makes it very difficult task in a terminal.

Linux comes with a very powerful built-in tool called rename. The rename command is used to rename multiple or group of files, rename files to lowercase, rename files to uppercase and overwrite files using perl expressions.

The “rename” command is a part of Perl script and it resides under “/usr/bin/” on many Linux distributions. You can run “which” command to find out the location of rename command.

The Basic Syntax of Rename Command

The rename command comes with few optional arguments along with mandatory perl expression that guides rename command to do actual work.

  1. -v: Print names of files successfully renamed.
  2. -n: Show what files would have been renamed.
  3. -f: Force overwrite existing files.
  4. perlexpr: Perl Expression.

For better understanding of this utility, we’ve discussed few practical examples of this command in the article.

1. A Basic Rename Command Example

Suppose you’ve bunch of files with “.html” extension and you want to rename all “.html” files to “.php” at one go. For example, first do a “ls -l” to check the list of files with “.html” extension.

Now, you want to change the extension of all these files from “.html” to “.php“. You can use the following “rename” command with perl expression as shown below.

Note: In the above command we’ve used two arguments.

  1. First argument is a perl expression that substitute .html with .php.
  2. Second argument tells the rename command to substitute all the files with *.php.

Let’s verify whether all files are renamed to “.php” extension, doing ls -l on the prompt.

Now you can see above that all the html files are renamed to php.

2. Check Changes Before Running Rename Command

While doing critical or major renaming tasks, you can always check the changes by running rename command with “-n” argument. The “-n” parameter will tell you exactly what changes would take place, but the changes are not done for real. Here, is the example of the command below.

Note: The above command output only displays changes, but in real the changes are not done, unless you run the command without “-n” switch.

3. Print Rename Output

We saw that the rename command didn’t displayed any information of changes it does. So, if you want to get the details of rename command (like we did using “-n” option), here we use “-v” option to print the complete details of all the changes done by rename command successfully.

4. Convert all Lowercase to Uppercase and Vise-Versa

To batch rename all files with lower case names to upper case. For example, I want to covert all these following files from lower to upper case.

Lower to Upper Case

Just, use the following command with perl expression.

Once you’ve executed the above command, you can check the changes by doing “ls -l“.

You can see that the above command actually renamed all the lower case file names (with .HTML extension) to upper case.

Upper to Lower Case

Similarly, you can also convert all upper case characters to lower case using the following command.

5. Capitalize First Letter of Filename

To capitalize only first letter of each filename use the following command.

Capitalize First Letter Filename

6. Overwrite Existing Files

If you would like to forcefully overwrite existing files, use the “-f” option as shown below.

If you would like to know more about rename command, type the “man rename” in the terminal.

The rename command is very useful, if you are dealing with multiple or batch renaming of files from the command line. Do give a try and let me know, how far is useful in terms of renaming of files.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Читайте также:  Операционная система windows диалоговое окно
Оцените статью