blob: fc21b986ba5fa1a8d80fc1be0a54ca1ec1d8ed33 [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# -l == remove shortest from left
24# -L == remove longest from left
25# -r == remove shortest from right (the default)
26# -R == remove longest from right
27
28substr()
29{
30 local flag pat str
31 local usage="usage: substr -lLrR pat string or substr string pat"
32 local options="l:L:r:R:"
33
34 OPTIND=1
35 while getopts "$options" c
36 do
37 case "$c" in
38 l | L | r | R)
39 flag="-$c"
40 pat="$OPTARG"
41 ;;
42 '?')
43 echo "$usage"
44 return 1
45 ;;
46 esac
47 done
48
49 if [ "$OPTIND" -gt 1 ] ; then
Chet Rameyac50fba2014-02-26 09:36:43 -050050 shift $(( $OPTIND -1 ))
Jari Aalto726f6381996-08-26 18:22:31 +000051 fi
52
Jari Aaltob80f6442004-07-27 13:29:18 +000053 if [ "$#" -eq 0 ] || [ "$#" -gt 2 ] ; then
Jari Aalto726f6381996-08-26 18:22:31 +000054 echo "substr: bad argument count"
55 return 2
56 fi
57
58 str="$1"
59
60 #
61 # We don't want -f, but we don't want to turn it back on if
62 # we didn't have it already
63 #
64 case "$-" in
65 "*f*")
66 ;;
67 *)
68 fng=1
69 set -f
70 ;;
71 esac
72
73 case "$flag" in
74 -l)
75 str="${str#$pat}" # substr -l pat string
76 ;;
77 -L)
78 str="${str##$pat}" # substr -L pat string
79 ;;
80 -r)
81 str="${str%$pat}" # substr -r pat string
82 ;;
83 -R)
84 str="${str%%$pat}" # substr -R pat string
85 ;;
86 *)
87 str="${str%$2}" # substr string pat
88 ;;
89 esac
90
91 echo "$str"
92
93 #
94 # If we had file name generation when we started, re-enable it
95 #
96 if [ "$fng" = "1" ] ; then
97 set +f
98 fi
99}