guskenny83 guskenny83 - 1 year ago 126
Linux Question

How can I extract the filename without extension (and add a counter) from a variable on the Linux command line?

I want to do a batch convert and resize of some images in a folder on the Linux (Mint 17) command line, so I am using:

for $file in *.jpg; do convert -resize 25% $file $file.png; done

but that leaves me with a bunch of files like:


is there a way that I can easily clip the file extension from the file name so that it only has the
instead of the preceding
as well?

or, better yet, can I include a counter so that I can run the command with something like this:

for $file in *.jpg using $count; do convert -resize 25% $file image$count.png; done

so that I end up with something like:


I'd rather not have to worry about creating a batch script, so if that is too hard and there is a simple way of just removing the
inline, then I'm happy with that..



I think this question is okay to be a question in it's own right because it also has a counter element.

Answer Source
$ ls *.jpg
DSCa_.jpg*  DSCb_.jpg*  DSCc_.jpg*
$ count=0; for file in *.jpg; do (( count++ )); convert -resize 25% "$file" "${file%\.*}$count.png"; done
$ ls *.png
DSCa_1.png  DSCb_2.png  DSCc_3.png

${file%\.*} uses parameter substitution to remove the shortest matching string from the right of $file. You can read more about parameter substitution here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download