简体   繁体   中英

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.

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

Something like this?

i=image1.jpg
echo ${i/.jpg/.png}
image1.png
$ 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

另外,您可以使用命令basename (文件名中的带后缀):

for file in *.jpg; do base=$( basename  ${file} .jpg); convert -resize 25% $file ${base}.png; done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM