#!/bin/bash (source) # ////////////////////////////////////////////////// # STRING OPERATIONS # ////////////////////////////////////////////////// function Is_Empty() { [ -z "$*" ] ;} # example: Starts_With "oper" "operations" function Starts_With() { l=${#1} [[ "${2:0:l}" = "$1" ]] } #detsch, 23/08/2004 # example: Ends_With "tions" "operations" function Ends_With() { l2=${#2} l3=$[ ${#2} - ${#1} ] [[ "${2:l3:l2}" = "$1" ]] } function Has_Uppercase() { echo "$1" | grep "[[:upper:]]" &> /dev/null } function Capitalize() { python -c " import sys,string word = sys.argv[1] def breakWord(word): for ch in ['-', '_']: pos = string.find(word, ch) if pos != -1: return [ word[:pos], ch ] + breakWord(word[pos+1:]) return [ word ] parts = breakWord(word) for part in parts: sys.stdout.write(string.capitalize(part)) " "$1" } # Split_String # splits a string into an array and places the result in the varable specified # if is ommitted whitespace is used # Usage: # eval $(Split_String []) function Split_String { string_name="$1" string="$2" token="$3" if [ -z "$token" ] then token=" " string=$(echo "${string}" | sed -r 's/\s+/ /g') fi echo -n "${string_name}=(" while index=$(expr index "${string}" "${token}") [ $index -gt 0 ] do echo -n "\"${string:0:((index-1))}\" " string="${string:index}" done echo -n "\"${string}\"" echo ")" } # obsolete? #function Split() { # python -c " # #import sys,string #sys.stdout.write(string.split(sys.argv[1])) # #" "$1" #} #detsch, 23/08/2004 # shell/sed/awk/cut implementation is welcome, but don't forget # negative values at "$3" #function Get_Token() { # python -c " #import sys,string #sys.stdout.write(string.split(sys.argv[1], sys.argv[2])[int(sys.argv[3])]) #" "$1" "$2" "$3" #} # splits $1 by $2, returns entry $3 (may be negative) function Get_Token() { local i=0 tokens=() len=${#2} local start rest=$1 while [ "$rest" ] do start=${rest%%$2*} if [ $i -eq $3 ] then echo -n $start return 0 fi tokens[$i]=$start rest=${rest:${#start}} if [ "$rest" ] then rest=${rest:$len} let i++ fi done [ $3 -lt 0 ] && echo -n ${tokens[$(( $i+$3+1 ))]} } # writes each string passed to it, but with the last character removed. function Chop() { echo -n "$(echo "$*" | sed -re "s/(.*)./\1/g")" } # Returns the arguments passed to it converted to lower case function Downcase() { echo "$*" | tr '[:upper:]' '[:lower:]' } function Uppercase() { echo "$*" | tr '[:lower:]' '[:upper:]' } function String_Revision() { Parameters "$@" versionandrevision echo $versionandrevision | sed -nr 's,.*-(r[0-9]+(p[0-9]+)?)$,\1,p' } function String_Version() { Parameters "$@" versionandrevision echo $versionandrevision | sed -r 's/-r[0-9]+(p[0-9]+)?$//g' }