Function index return the position of substring in string counting from
one and 0 if substring is not found.
这个很容易误解,indeX 指的是 substring中的字符最早在 string 出现的位置
expr index $string $substring
Numerical position in $string of first character in $substring that
matches.
stringZ=abcABC123ABCabc
echo `expr index "$stringZ" C12` # 6
# C position.
echo `expr index "$stringZ" c` # 3
# 'c' (in #3 position)
|
This is the near equivalent of strchr() in C.
expr substr $string $position
$length
Extracts
$length characters from
$string
starting at
$position.. The first character has index
one.
stringZ=abcABC123ABCabc
# 123456789......
# 1-based indexing.
echo `expr substr $stringZ 1 2` # ab
echo `expr substr $stringZ 4 3` # ABC
|
Determining the Length of Matching Substring at Beginning of String
This is pretty rarely used capability of expr built-in but still
sometimes it can be useful:
expr match "$string" '$substring'
where:
- String is any variable of literal string.
- $substring is a
.
stringZ=abcABC123ABCabc
# |------|
echo `expr match "$stringZ" 'abc[A-Z]*.2'` # 8
echo `expr "$stringZ" : 'abc[A-Z]*.2'` # 8
There are several ways to get length of the string.
-
The simplest one is ${#varname},
which returns the length of the value of the variable as a character
string. For example, if filename has the value fred.c,
then ${#filename} would have the value 6.
-
The second is to use built in function expr, for example
expr length $string or expr "$string" : '.*'
- Additional examples from
stringZ=abcABC123ABCabc
echo ${#stringZ} # 15
echo `expr length $stringZ` # 15
echo `expr "$stringZ" : '.*'` # 15
- More complex example. Here's the function for validating
that that string is within a given max length. It requires two parameters,
the actual string and the maximum length the string should be.check_length()
# check_length
# to call: check_length string max_length_of_string
{
# check we have the right params
if (( $# != 2 )) ; then
echo "check_length need two parameters: a string and max_length"
return 1
fi
if (( ${#1} > $2 )) ; then
return 1
fi
return 0
}
You could call the function check_length like this:
#!/usr/bin/bash
# test_name
while :
do
echo -n "Enter customer name :"
read NAME
[ check_length $NAME 10 ] && break
echo "The string $NAME is longer then 10 characters"
done
echo $NAME
阅读(513) | 评论(0) | 转发(0) |