how to check whether a string starts with xx and ends with yy in shellscript?

128 views Asked by At

In the below example I want to find whether the sentence starts with 'ap' and ends with 'e'.

example: a="apple"

if [[ "$a" == ^"ap"+$ ]]

This is not giving proper output.

1

There are 1 answers

0
Shawn On

You don't mention which shell you're using, but the [[ in your attempt suggests you're using one that expands upon the base POSIX sh language. The following works with at least bash, zsh and ksh93:

$ a=apple
$ [[ $a == ap*e ]] && echo matches # Wildcard pattern
matches
$ [[ $a =~ ^ap.*e$ ]] && echo matches # Regular expression - note the =~
matches