shell script how to compare file name with expected filename but different extention in single line

StackOverflow https://stackoverflow.com/questions/23284303

  •  09-07-2023
  •  | 
  •  

Pregunta

I have doubt in shell script
I will describe the scenario, $file is containing the file name of my interest,
consider $file can contain foo.1, foo.2, foo.3 here foo will be constant,
but .1,.2,.3 will change, i want to test this in single line in if statement something like

if [ $file = "foo.[1-9]" ]; then
echo "File name is $file"
fi'

i know above script doesn't work :) can anyone suggest what should i refer for this ?

¿Fue útil?

Solución 2

Use [[ instead for regex matching.

if [[ $file =~ ^foo\.[1-9]$ ]] ; ...

Otros consejos

Trim any extension, then see if it's "foo"?

base=${file%.[1-9]}
if [ "$base" = "foo" ]; then
    echo Smashing success
fi

Equivalently, I always like to recommend case because it's portable and versatile.

case $file in
    foo.[1-9] ) echo Smashing success ;;
esac

The syntax may seem weird at first but it's well worth knowing.

Both of these techniques should be portable to any Bourne-compatible shell, including Dash and POSIX sh.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top