Creating output file name from input file in bash

I have a bash script:

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

Instead of passing two arguments when running the script, I want to mention only the source name (or the name of the input file), and the name of the output file should be automatically multiplied from the name of the source file. Something like this "$1" | cut -d'.' -f1".jpg" "$1" | cut -d'.' -f1".jpg" "$1" | cut -d'.' -f1".jpg" . If the input file name was myimage.png , the output name should be myimage.jpg . .jpg should be added to the first part of the source file name. It should also work if the argument is *.png . So how can I change my script?

+4
source share
3 answers

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

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

To work with multiple files:

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

This will result in a jump for each command line argument and abbreviation for for filename in " $@ " . You don't have to worry about checking if the *.png argument is - the shell will expand it for you - you just get an extended list of file names.

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

The magic is in the %.* Part, which removes everything after the last point . If your file does not have an extension, it will still work (as long as you don’t have a point elsewhere on the path).

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

Source: https://habr.com/ru/post/1345831/


All Articles