开发者

Generating the output file name from the input file in bash

开发者 https://www.devze.com 2023-02-20 13:13 出处:网络
I have a bash script: #!/bin/bash convert \"$1\" -resize 50% \"$2\" Instead of passing two arguments while the script is run I want to mention just the source (or input file name) and the output fi

I have a bash script:

#!/bin/bash
convert "$1" -resize 50% "$2"

Instead of passing two arguments while the script is run I want to mention just the source (or input file name) and the output file name should be auto-genarated from the source file name. Something like this "$1" | cut -d'.' -f1".jpg". If the input file name was myimage.png, the output name should be myimage.jp开发者_C百科g. .jpg should be appended to the fist part of the source file name. It should also work if the argument is: *.png. So how can I modify my script?


The expansion ${X%pattern} removes pattern of the end of $X.

convert "$1" -resize 50% "${1%.*}.jpg"

To work on multiple files:

for filename ; do
    convert "$filename" -resize 50% "${filename%.*}.jpg"
done

This will iterate over each of the command line arguments and is shorthand for for filename in "$@". You do not need to worry about checking whether the argument is *.png - the shell will expand that for you - you will simple receive the expanded list of filenames.


convert "$1" -resize 50% "${1%.*}.jpg"

The magic is in the %.* part, which removes everything after the last dot. If your file is missing an extension, it will still work (as long as you don't have a dot anywhere else in the path).


OUTFILE=`echo $1|sed 's/\(.*\)\..*/\1/'`.jpg
convert "$1" -resize 50% "$OUTFILE"
0

精彩评论

暂无评论...
验证码 换一张
取 消