How to test if part of a string matches?

How to test if the first 7 characters of a string matches "backup."?

This did not work:

#!/bin/sh
name="backup.20091122"
if [ "${$name | cut -c 1-7}" = "backup." ]
then
    echo name is a backup
else
    echo name is not a backup
fi

Thank you.

if [ "$( echo $name | cut -c 1-7 )" = "backup." ]
if [ "${name%.*}." = "backup." ]
[[ $name == @(backup[\.])* ]] && echo yes 
yes

---------- Post updated at 12:44 PM ---------- Previous update was at 12:40 PM ----------

[[ $name == @(backup[\.][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]) ]] && echo yes
yes

If you want the date as well

works in either bash or ksh93

name=backup.12345678
[[ ${name:0:7} == backup. ]] && echo "yes"
# name=backup.12345678
# case $name in backup* ) echo "yes";; esac

Thank you for the wide range of solutions. But what shell are you using? I am using borne shell.

---------- Post updated at 02:08 PM ---------- Previous update was at 01:48 PM ----------

Where can I learn more about the "%.*" syntax? Or what key words can I google to read about the syntax?

Thank you.

parameter expansion (bash/ksh/sh)

Hi wolfv, probably your system does not use the classic Bourne Shell anymore. Most systems now have a /bin/sh that is Posix compliant with several enhancements, one of which is pattern-matching operators (a kind of parameter expansion).

Hi Scrutinizer. I am new at unix/linux. I am using sh on Ubuntu. What is the name of the sh shell?

Thank you.

Hi wolfv,

It is called dash (Debian Almquist shell).

S.

Hi Scrutinzer,
I am running dash. What is the "%" for?

That was answered earlier in the thread:
http://www.unix.com/shell-programming-scripting/121539-how-test-if-part-string-matches.html\#post302362779

Like bash and ksh, dash is a POSIX shell.

Hi wolfv, % means remove smallest suffix pattern. In this case the suffix pattern is ".*" , which means a dot followed by any amount characters. In other words, chop off the dot and any trailing characters at the end. See here.

Thank you for all your help Scrutinzer. Here is the code I used:

#!/bin/sh
name="backup-091017-112436"

if [ "${name%-[0-9][0-9][0-1][0-9][0-3][0-9]-[0-2][0-9][0-6][0-9][0-6][0-9]}" = "backup" ]
then
	echo name is a backup
else
	echo name is not a backup
fi

Great, not much can go wrong with such a tight match. If there is no variation in file names and they are always backup-yymmdd-hhmmss anyway, you could get away with:

${name%-*-*}

or

${name%%-*}