Bash – Selecting non-existent files with wildcard/regex

argumentsbashregular expressionshellshell-script

I'm trying to convert hundreds of *.jpg files to *.webp files with libwebp on macOS. Particularly, I want to use the command line tool cwebp to perform the conversion. It works like this:

cwebp <input_file>.jpg -o <output_file>.webp

My *.jpg files, whose names are IMG_20160227_110640.jpg or so, are stored under a directory called root. The problem is that *.webp files does not exist when the conversion is performed, so I don't know how to pass their names to cwebp. For example, if I only have one picture to convert, I would simple execute

cwebp IMG_20160227_110640.jpg -o IMG_20160227_110640.webp

However, there are hundreds of them, and I don't want to type hundreds lines of command. How to use a regular expression / write a script to automate the conversion?

Best Answer

Use a for loop combined with parameter expansion:

for f in *.jpg; do cwebp "$f" -o "${f%.jpg}.webp"; done

See also LESS='+/Parameter Expansion' man bash to read up on this for Bash.

However, Parameter Expansion is specified in POSIX; it is not specific to Bash. (Bash may have some extensions, though.) The command above will work on any POSIX system.

Related Question