2bb8d363037acd84ddf54e205d60dc97c7eef952
[platform/upstream/bash.git] / examples / functions / substr2
1 #
2 # substr -- a function to emulate the ancient ksh builtin
3 #
4
5 # -l == remove shortest from left
6 # -L == remove longest from left
7 # -r == remove shortest from right (the default)
8 # -R == remove longest from right
9
10 substr()
11 {
12         local flag pat str
13         local usage="usage: substr -lLrR pat string or substr string pat"
14         local options="l:L:r:R:"
15
16         OPTIND=1
17         while getopts "$options" c
18         do
19                 case "$c" in
20                 l | L | r | R)
21                         flag="-$c"
22                         pat="$OPTARG"
23                         ;;
24                 '?')
25                         echo "$usage"
26                         return 1
27                         ;;
28                 esac
29         done
30
31         if [ "$OPTIND" -gt 1 ] ; then
32                 shift $[ $OPTIND -1 ]
33         fi
34
35         if [ "$#" -eq 0 ] || [ "$#" -gt 2 ] ; then
36                 echo "substr: bad argument count"
37                 return 2
38         fi
39
40         str="$1"
41
42         #
43         # We don't want -f, but we don't want to turn it back on if
44         # we didn't have it already
45         #
46         case "$-" in
47         "*f*")
48                 ;;
49         *)
50                 fng=1
51                 set -f
52                 ;;
53         esac
54
55         case "$flag" in
56         -l)
57                 str="${str#$pat}"               # substr -l pat string
58                 ;;
59         -L)
60                 str="${str##$pat}"              # substr -L pat string
61                 ;;
62         -r)
63                 str="${str%$pat}"               # substr -r pat string
64                 ;;
65         -R)
66                 str="${str%%$pat}"              # substr -R pat string
67                 ;;
68         *)
69                 str="${str%$2}"                 # substr string pat
70                 ;;
71         esac
72
73         echo "$str"
74
75         #
76         # If we had file name generation when we started, re-enable it
77         #
78         if [ "$fng" = "1" ] ; then
79                 set +f
80         fi
81 }