guskenny83 guskenny83 - 1 month ago 12
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:

image1.jpg.png
photo4.jpg.png
picture7.jpg.png
...


is there a way that I can easily clip the file extension from the file name so that it only has the
.png
instead of the preceding
.jpg
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:

image1.png
image2.png
image3.png
image4.png
...


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
.jpg
inline, then I'm happy with that..

thanks!

EDIT:

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

Answer
$ 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

Comments