27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

#:docstring strspn:<br />

# Usage: strspn $s1 $s2<br />

#<br />

# Strspn returns the length of the maximum initial segment of string s1,<br />

# which consists entirely of characters from string s2.<br />

#:end docstring:<br />

###;;;autoload<br />

function strspn ()<br />

{<br />

# Unsetting IFS allows whitespace to be handled as normal chars.<br />

local IFS=<br />

local result="${1%%[!${2}]*}"<br />

}<br />

echo ${#result}<br />

#:docstring strcspn:<br />

# Usage: strcspn $s1 $s2<br />

#<br />

# Strcspn returns the length of the maximum initial segment of string s1,<br />

# which consists entirely of characters not from string s2.<br />

#:end docstring:<br />

###;;;autoload<br />

function strcspn ()<br />

{<br />

# Unsetting IFS allows whitspace to be handled as normal chars.<br />

local IFS=<br />

local result="${1%%[${2}]*}"<br />

}<br />

echo ${#result}<br />

#:docstring strstr:<br />

# Usage: strstr s1 s2<br />

#<br />

# Strstr echoes a substring starting at the first occurrence of string s2 in<br />

# string s1, or nothing if s2 does not occur in the string. If s2 points to<br />

# a string of zero length, strstr echoes s1.<br />

#:end docstring:<br />

###;;;autoload<br />

function strstr ()<br />

{<br />

# if s2 points to a string of zero length, strstr echoes s1<br />

[ ${#2} −eq 0 ] && { echo "$1" ; return 0; }<br />

# strstr echoes nothing if s2 does not occur in s1<br />

case "$1" in<br />

*$2*) ;;<br />

*) return 1;;<br />

esac<br />

# use the pattern matching code to strip off the match and everything<br />

# following it<br />

first=${1/$2*/}<br />

}<br />

# then strip off the first unmatched portion of the string<br />

echo "${1##$first}"<br />

Appendix A. Contributed Scripts 394

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!