bash choping strings

#!/bin/bash
 
# http://www.ibm.com/developerworks/library/l-bash.html
# how to chopping strings?
 
# basename and dirname
path='/usr/local/share/doc/foo.txt'
 
basename $path   # foo.txt
echo ${path##*/} # foo.txt
 
dirname $path    # /usr/local/share/doc
echo ${path%/*}  # /usr/local/share/doc
 
# professional chopping
var="somestring"
 
echo ${var#*s}  # omestring
echo ${var##*s} # tring
 
echo ${var%s*}  # some
echo ${var%%s*} # null!
 
echo ${var%%ng*} # somestri
echo ${var%%ing} # somestr
 
echo ${var:0:4}  # some

Search and replace on variables:

var="somestring"
echo ${var/some/any} # anystring
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">