blob: f19f5d7ec0db13afcbe5a8d1bc89d05232735eb8 [file] [log] [blame]
Jari Aalto726f6381996-08-26 18:22:31 +00001#
Chet Rameyac50fba2014-02-26 09:36:43 -05002# Chet Ramey <chet.ramey@case.edu>
3#
4# Copyright 2002 Chester Ramey
5#
6# This program is free software; you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation; either version 2, or (at your option)
9# any later version.
10#
11# TThis program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program; if not, write to the Free Software Foundation,
18# Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19#
Jari Aalto726f6381996-08-26 18:22:31 +000020# substr -- a function to emulate the ancient ksh builtin
21#
22
23#
24# -l == shortest from left
25# -L == longest from left
26# -r == shortest from right (the default)
27# -R == longest from right
28
29substr()
30{
31 local flag pat str
32 local usage="usage: substr -lLrR pat string or substr string pat"
33
34 case "$1" in
35 -l | -L | -r | -R)
36 flag="$1"
37 pat="$2"
38 shift 2
39 ;;
40 -*)
41 echo "substr: unknown option: $1"
42 echo "$usage"
43 return 1
44 ;;
45 *)
46 flag="-r"
47 pat="$2"
48 ;;
49 esac
50
Jari Aaltob80f6442004-07-27 13:29:18 +000051 if [ "$#" -eq 0 ] || [ "$#" -gt 2 ] ; then
Jari Aalto726f6381996-08-26 18:22:31 +000052 echo "substr: bad argument count"
53 return 2
54 fi
55
56 str="$1"
57
58 #
59 # We don't want -f, but we don't want to turn it back on if
60 # we didn't have it already
61 #
62 case "$-" in
63 "*f*")
64 ;;
65 *)
66 fng=1
67 set -f
68 ;;
69 esac
70
71 case "$flag" in
72 -l)
73 str="${str#$pat}" # substr -l pat string
74 ;;
75 -L)
76 str="${str##$pat}" # substr -L pat string
77 ;;
78 -r)
79 str="${str%$pat}" # substr -r pat string
80 ;;
81 -R)
82 str="${str%%$pat}" # substr -R pat string
83 ;;
84 *)
85 str="${str%$2}" # substr string pat
86 ;;
87 esac
88
89 echo "$str"
90
91 #
92 # If we had file name generation when we started, re-enable it
93 #
94 if [ "$fng" = "1" ] ; then
95 set +f
96 fi
97}