Once and for All: substrings & substitiution in bash/zsh

Great shell foo (and a bit of imagemagick)

This is the first post in the new Once-And-For-All category. Maybe it’s just me who keeps forgetting commands and syntax from one use to the other. I don’t know how often I already googled simple basic actions like bash-syntax only to forget the the other week. Now to avoid future googling I decided to write a post.

Today’s episode: Batch-renaming and conversion of all PNG-files in current folder to a 128x128 pixel JPEG using ImageMagick ‘convert’ (foo.png –> foo.jpg)

for file in $(ls *.png );
do
convert $file -quality 90 -filter Gaussian -resize 128x128 ${file%.png}.jpg ;
done

Note:

  1. ‘%’ matches the longest substring form the back of the variable (greedy).
  2. ‘#’ matches the shortest substring form the back of the variable (non-greedy).
  3. ‘%%’ matches the longest substring form the front of the variable (greedy).
  4. ‘##’ matches the shortest substring form the front of the variable (non-greedy).

Alternatively you can give a ‘regexp’ ${text/pattern/substition}. But since bash has it’s own syntax (see above) for regexp which I don’t bother to learn I will stick with sed if I need regular expressions.

On most Linux-distributions you probably have the command ‘rename’. As the name already suggests, a tool for renaming a files. Very handy since it workes with perl regular expressions (rename’s author is Larry Wall).

Form the manpage :

rename [ -v ] [ -n ] [ -f ] perlexpr [ files ] For example, to rename all files matching “*.bak” to strip the extension, you might say rename ’s/.bak$//' *.bak