- 6 способов переименования нескольких файлов сразу в Linux
- Переименование нескольких файлов сразу в Linux
- Метод 1 – Использование mmv
- Способ 2. Использование утилиты rename
- Mass renaming files on Linux
- Rename
- Bash Magic
- Use Midnight Commander to Rename Multiple Files
- Thunar mass rename
- How can I mass rename files in Linux containing spaces? [duplicate]
- 3 Answers 3
- Mass rename files linux
- How do you mass rename files in Linux? [duplicate]
- 3 Answers 3
- Not the answer you’re looking for? Browse other questions tagged linux bash or ask your own question.
- Linked
- Related
- Hot Network Questions
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 для отображения тех переименований, которые будут выполняться без их выполнения:
Как вы можете видеть, приведенная выше команда не вносила никаких изменений, а просто отображает имена переименованных файлов.
Вы можете принудительно переименовать задачу, даже если операция будет перезаписывать существующие файлы с использованием флага -f, как показано ниже.
Если вы не хотите перезаписывать файлы, вы можете просто преобразовать их в заглавные или строчные буквы (и наоборот), чтобы предотвратить «уже существующие» ошибки.
Чтобы преобразовать все имена файлов в нижний регистр:
Давайте проверим, были ли внесены изменения.
Да, буквы в именах файлов были изменены с нижнего регистра на верхний регистр.
Аналогично, чтобы преобразовать имена файлов в нижний регистр, выполните:
Мы также можем удалить все пустые ячейки в имени файла.
Например, у меня есть следующий файл.
Чтобы удалить все пробелы в указанном выше имени файла, запустите:
Теперь имя файла не имеет пробелов.
Заменить пробелы символами подчеркивания:
Возможно, вы захотите изменить расширение файла, но не переименовать имена файлов.
Это также возможно.
Следующая команда переименовала бы все * .txt-файлы в * .doc.
Проверьте изменения с помощью команды ls:
Чтобы удалить расширение во всех файлах, соответствующих .txt, запустите:
Для получения дополнительной информации см. Справочные страницы.
Источник
Mass renaming files on Linux
Mass renaming files is no possible with the standard linux command mv , but it’s possible to achieve this goal in many different ways, from some bash magic, to programs that do exactly this, in this article I’ll work with both the terminal and with graphical tools.
First example, you have these files:
myconf.sh myfile2.txt anotherfile.sh test.sh
And you want to add to all the files that end with .sh a .bak, these are some possible solutions
Rename
rename perlexpr [ files ]
rename is a perl script which can be used to mass rename files according to a regular expression.
The perlexpr argument is a Perl expression which is expected to modify the $_ string in Perl for at least some of the filenames specified. If a given filename is not modified by the expression, it will not be renamed. If no filenames are given on the command line, filenames will be read via standard input.
So in our case we could use
rename ‘s/.sh/.sh.bak/g’ *.sh
The expression ‘s/.sh/.sh.bak/g’ means:
s=substitute.
/.sh/=string to search for substitution.
/.sh.bak/ = new string that will be put in place.
g=global, does this for every occurrence of the string.
This will substitute the string .sh to .sh.bak, so we’ll get exactly what we want:
anotherfile.sh.bak myconf.sh.bak myfile2.txt test.sh.bak
mmv , is a program to move/copy/append/link multiple files according to a set of wildcard patterns. This multiple action is performed safely, i.e. without any unexpected deletion of files due to collisions of target names with existing filenames or with other target names. Furthermore, before doing anything, mmv attempts to detect any errors that would result from the entire set of actions specified and gives the user the choice of either aborting before beginning, or proceeding by avoiding the offending parts.
This command has many options that can do different things, like moving in sub-directories and do a safe copy of every file they touch, but for our small example you could simply use this command:
Bash Magic
With bash commands you can do almost anything in many different ways, so I’ll just show 1 simple way to rename multiple files using the standard mv command.
for i in *.sh; do mv $i `basename $i sh`sh.bak; done
This small example uses the command basename , that print the name of the file given as argument with any leading directory components removed and in this case removes the trailing suffix, to add to the file another one.
Use Midnight Commander to Rename Multiple Files
GNU Midnight Commander (also known as MC) is a free cross-platform orthodox file manager and a clone of Norton Commander using it you can rename multiple files as explained below.
- Select the required files using regular expression. Press + which will ask the regex to select files. For example, giving *.sh will highlight all the files with .sh extension.
- Rename all the selected files using regex. Press F6 which will ask for the source and destination regex, doing so will change the file names. For this example, give *.sh in source and *.sh.bak in destination which will rename do what we need.
Thunar mass rename
Thunar is a file manager for Linux and other Unix-like systems, written using the GTK+ 2 toolkit, and shipped with Xfce version 4.4 RC1 and later. To rename file with Thunar just follow these simple instructions:
Open thunar on the directory where your files are located and select all of them
Now press F2 or go in Edit -> Rename to start the Bulk Renamer dialog box that has many different options:
Audio Tags – Lets you modify file names based on the ID3 tags
Insert Date/Time – To insert in your files the date and time.
Insert/Overwrite – Allows you to put a piece of information somewhere in the title of the file, or replace part of the file name with entirely new text.
Numbering – To insert a number at the start of every file
Remove Characters – Allows you to get rid characters, useful to remove spaces or underscore.
Search & Replace – This is the most powerful tool and you can use regexp with it.
Uppercase/Lowercase – This option allow you to “normalize” a text, so you could make it all lowercase.
Choose Search & Replace, search for .sh and replace with .sh.bak, all done !
Thunar is just one of the graphical tool that you can use, it’s possible to use also Nautilus and specific tools such as:
KRename
KRename is a powerful batch renamer for KDE. It allows you to easily rename hundreds or even more files in one go.
GPRename
GPRename is a complete batch renamer for files and directories
Источник
How can I mass rename files in Linux containing spaces? [duplicate]
I want to rename all of the pdf files that contains spaces by replacing them by underscores. So I invoke the command:
and I got errors on the terminal:
So what is wrong in the command?
3 Answers 3
Get the Perl-based rename command (sometimes called prename ) to do the job:
The shell globbing keeps each file name separate; the prename command does bulk renaming; the s/ /_/g operation replaces each blank by _ everywhere in the file name. (The original code only replaces the first blank with an underscore, and then runs foul of xargs breaking on white space (blanks and tabs as well as newlines.)
You could try quoting the filenames:
This is probably how you’re doing it by hand, as well:
Relying on pure bash, you’d have to use a for-loop and bash substitutions:
First of all, your sed command does not match any files because you are trying to match quote-space-quote instead of just a space . Unless you have a file literally named A» «file.pdf , you will not match it with sed .
Let’s say you’ve fixed it to sed -e ‘p; ‘s/ /_/g’ . If you have a file called A file.pdf , your output will be
and these you pass as arguments to xargs . However, xargs is instructed to take the first two arguments. In this case they will be A and file.pdf , neither of which exist, and therefore mv cannot stat them!
Here is, in my opinion, an easier way to do it:
Источник
Mass rename files linux
Итак, у нас есть куча файлов, среди которых надо навести порядок. Для этого сделаем групповое переименование.
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 do you mass rename files in Linux? [duplicate]
there are 30 files named like this:
I need the output to be:
I don’t know how to do this, I’ve already screwed the names up a lot. thanks for any help.
3 Answers 3
Use the rename utility:
rename is part of the perl package and is installed by default on debian-like systems. There is a different and incompatible rename utility that is provided as part of the util-linux packages.
If you have the Perl-based prename (possibly named rename ) command, then:
The exact regex to use depends on how the names have been damaged. This should work for the example name given; it may need tweaking to work with other names.
You could use a for loop. Since I’m always nervous about this stuff I’d recommend doing an echo first to make sure everything looks groovy.
Provided that doesn’t need tweaking, you can remove the echo or make modifications as necessary.
Not the answer you’re looking for? Browse other questions tagged linux bash or ask your own question.
Linked
Related
Hot Network Questions
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.8.40416
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник