Once-And-For-All: substrings & substitiution in Bash

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 128×128 pixel JPEG using ImageMagick ‘convert’ (foo.png –> foo.jpg) :

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

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

Here are some more information: www.thegeekstuff.com

1 comment

    • Niko E on 2013-08-05 at 09:03

    Hi Ruschi,

    nice to see other people are running into the same problems 😉

    Just a small side note, as I’ve crossed this issue already a couple of times: you’re probably used to work on Debian based Linux systems (so am I), however on e.g. RedHat/CentOS the “rename” tool is slightly different and less nice to operate. Turns out that “rename” in Debian symlinked from /usr/bin/rename -> /etc/alternatives/rename -> /usr/bin/prename, which is in turn part of Debian’s “perl” package.

    Unfortunately, RedHat or CentOS don’t provide the much nicer “prename” tool, even though “perl” is installed. No clue about SuSE and others…


Comments have been disabled.