简体   繁体   English

在Linux Shell命令中替换输出文件扩展名

[英]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,它需要一些输入jpeg,并在同一目录中吐出一个新的png:

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

I want to make an alias "convertToPng" which takes only one arg, the file: 我想做一个别名“ convertToPng”,它只需要一个arg,即文件:

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". 但是,这会将输出文件命名为“ photo.jpg.png”,我希望将其命名为“ photo.png”。 Is there any way to parse the filename first, and then pass that to the convertImage executable? 有什么办法可以先解析文件名,然后将其传递给convertImage可执行文件?

If your input is always jpg then 如果您的输入始终为jpg,则

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 或在您的.bashrc编写一个函数,如下所示

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

and execute above function as 并执行上述function

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. 我更喜欢function方式,因为它给您提供了比aliases更大的灵活性,并且您不仅可以执行一条语句,还可以执行更多操作。

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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