Ksh-style left and right line separating to a consistent expression?

How can I separate the left parts and the right parts from lines to the corresponding expression, as in ksh?

For instance:

${name##*/}

${name%/*}

(see http://www.well.ox.ac.uk/~johnb/comp/unix/ksh.html for ksh examples).

I cannot imagine an easy way to do this using the re module or string module, but something is missing for me.

+5
source share
4 answers

KS:

$ s='abc/def/ghi'
$ echo ${s%%/*}
abc
$ echo ${s%/*}
abc/def
$ echo ${s#*/}
def/ghi
$ echo ${s##*/}
ghi

Python:

>>> s='abc/def/ghi'
>>> print s[:s.find("/")]
abc
>>> print s[:s.rfind("/")]
abc/def
>>> print s[s.find("/")+1:]
def/ghi
>>> print s[s.rfind("/")+1:]
ghi

Edit:

To handle a case where a template is missing, as indicated by ΤΖΩΤΖ :

>>> s='abc/def/ghi'
>>> t='no slash here'
>>> print s[:s.find("/") % (len(s) + 1)]
abc
>>> print t[:t.find("/") % (len(t) + 1)]
no slash here
>>> print s[:s.rfind("/") % (len(s) + 1)]
abc/def
>>> print t[:t.rfind("/") % (len(t) + 1)]
no slash here
>>> print s[s.find("/")+1:]
def/ghi
>>> print t[t.find("/")+1:]
no slash here
>>> print s[s.rfind("/")+1:]
ghi
>>> print t[t.rfind("/")+1:]
no slash here
+3
source
${name##*/}

It is equivalent to:

re.match(".*?([^/]*)$")[1]

${name%/*}

It is equivalent to:

re.match("(.*?)[^/]*$")[1]
+2
source

" ", " " .. - re.sub - , " " ( "", ksh ):

name = re.sub(r'(.*/)(.*)', r'\2', name)

" " ( "" ksh):

name = re.sub(r'(.*)/.*', r'\1', name)

, * RE ; *? - ( " " ).

+2
>>> def strip_upto_max(astring, pattern):
    "${astring##*pattern}"
    return astring.rpartition(pattern)[2]
>>> def strip_from_max(astring, pattern):
    "${astring%%pattern*}"
    return astring.partition(pattern)[0]
>>> def strip_upto(astring, pattern):
    "${astring#*pattern}"
    return astring.partition(pattern)[2]
>>> def strip_from(astring, pattern):
    "${astring%pattern*}"
    return astring.rpartition(pattern)[0]

>>> strip_from("hello there", " t")
'hello'
>>> strip_upto("hello there", " t")
'here'

>>> text= "left/middle/right"
>>> strip_from(text, "/")
'left/middle'
>>> strip_upto(text, "/")
'middle/right'
>>> strip_upto_max(text, "/")
'right'
>>> strip_from_max(text, "/")
'left'

, , os.path.dirname (${name%/*}) os.path.basename (${name##*/}) .

+1

All Articles