简体   繁体   中英

Replace output file extension in linux shell command

Say I have a command, convertImage, which takes some input jpeg, and spits out a new png in the same directory:

convertImage --format png photo.jpg -o photo.png

I want to make an alias "convertToPng" which takes only one arg, the file:

convertToPng photo.jpg

My current solution is this:

alias convertToPng "convertImage --format png \!:1 -o \!:1.png"

However this will name the output file to "photo.jpg.png" and I want it to be named "photo.png". Is there any way to parse the filename first, and then pass that to the convertImage executable?

If your input is always jpg then

convertToPng photo
alias convertToPng "convertImage --format png \!:1.jpg -o \!:1.png"

or give extension as 2nd parameter

convertToPng photo jpg
alias convertToPng "convertImage --format png \!:1.\!:2 -o \!:1.png"

or last option

convertToPng photo.jpg
alias convertToPng "convertImage --format png \!:1 -o `echo $1 | cut -f1 -d'.'`.png"

or write a function in your .bashrc as follows

function convert() 
{
    convertImage --format png $1 -o `echo $1 | cut -f1 -d'.'`.png;
}

and execute above function as

convert photo.jpg

I prefer the function way as it gives you lot flexibility over aliases and you can do much more than just one statement.

echo photo.jpg | awk -F. '{print $1".png"}'

可以在命令行调用中使用它,如下所示:

$ convertImage --format png photo.jpg -o `echo photo.jpg | awk -F. '{print $1".png"}'`

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