У меня есть 3 файла в каталоге:
aaa.jpg
bbb.jpg
ccc.jpg
Я могу уменьшить изображение с помощью ImagkMagick convert:
convert aaa.jpg -resize 1200x900 aaa-small.jpg
Я хочу сделать все изображения в каталоге, что-то вроде:
convert *.jpg -resize 1200x900 *-small.jpg
, но в результате получаются файлы с таким именем:
*-small-0.jpg
*-small-1.jpg
*-small-2.jpg
Я хочу:
aaa-small.jpg
bbb-small.jpg
ccc-small.jpg
Как мне это сделать?
Это неприятно непрозрачно в документации, но вы можете передать процитированный глобус оболочки в convert
(в кавычках, чтобы оболочка не расширила его преждевременно), и используйте Процент экранирования имени файла для создания имен выходных файлов в форме % [имя файла: метка]
(где метка
- произвольная метка, заданная пользователем) с использованием входного escape-символа базового имени % [basename]
или его устаревшего эквивалента % t
:
$ ls ???.jpg
aaa.jpg bbb.jpg ccc.jpg
затем
$ convert '*.jpg' -set filename:fn '%[basename]-small' -resize 1200x900 '%[filename:fn].jpg'
, что приводит к
$ ls ???-small.jpg
aaa-small.jpg bbb-small.jpg ccc-small.jpg
В цикле for можно использовать функции, описанные в man bash
at
Parameter Expansion
...
${parameter%%word}
Remove matching suffix pattern. The word is expanded to produce a pattern just
as in pathname expansion. If the pattern matches a trailing portion of the
expanded value of parameter, then the result of the expansion is the expanded
value of parameter with the shortest matching pattern (the ``%'' case) or the
longest matching pattern (the ``%%'' case) deleted. If parameter is @ or *,
the pattern removal operation is applied to each positional parameter in turn,
and the expansion is the resultant list. If parameter is an array variable
subscripted with @ or *, the pattern removal operation is applied to each member
of the array in turn, and the expansion is the resultant list.
Следующая однострочная должна выполнять эту работу
for f in ./*.jpg ; do convert "$f" -resize 1200x900 "${f%.jpg}-small.jpg" ; done
Это работает в bash
, который является стандартной оболочкой Ubuntu. Я думаю, что это легче запомнить, чем элегантный метод Steeldriver (который использует только convert
и не for
).
mkdir small
for f in *.jpg ; do convert $f -resize 1200x900 small/$f ; done