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.

echo Number of digits at the beginning of \"$a\" is $b.<br />

b=`expr match "$a" '\([0−9]*\)'`<br />

# Note that escaped parentheses<br />

# == == + trigger substring match.<br />

echo "The digits at the beginning of \"$a\" are \"$b\"."<br />

echo<br />

exit 0<br />

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

The : operator can substitute for match. For example, b=`expr $a : [0−9]*` is the<br />

exact equivalent of b=`expr match $a [0−9]*` in the above listing.<br />

#!/bin/bash<br />

echo<br />

echo "String operations using \"expr \$string : \" construct"<br />

echo "==================================================="<br />

echo<br />

a=1234zipper5FLIPPER43231<br />

echo "The string being operated upon is \"`expr "$a" : '\(.*\)'`\"."<br />

# Escaped parentheses grouping operator. == ==<br />

# ***************************<br />

#+ Escaped parentheses<br />

#+ match a substring<br />

# ***************************<br />

# If no escaped parentheses...<br />

#+ then 'expr' converts the string operand to an integer.<br />

echo "Length of \"$a\" is `expr "$a" : '.*'`."<br />

# Length of string<br />

echo "Number of digits at the beginning of \"$a\" is `expr "$a" : '[0−9]*'`."<br />

# −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− #<br />

echo<br />

echo "The digits at the beginning of \"$a\" are `expr "$a" : '\([0−9]*\)'`."<br />

# == ==<br />

echo "The first 7 characters of \"$a\" are `expr "$a" : '\(.......\)'`."<br />

# ===== == ==<br />

# Again, escaped parentheses force a substring match.<br />

#<br />

echo "The last 7 characters of \"$a\" are `expr "$a" : '.*\(.......\)'`."<br />

# ==== end of string operator ^^<br />

# (actually means skip over one or more of any characters until specified<br />

#+ substring)<br />

echo<br />

exit 0<br />

This example illustrates how expr uses the escaped parentheses −− \( ... \) −− grouping operator in tandem<br />

with regular expression parsing to match a substring.<br />

Chapter 12. External Filters, Programs and Commands 157

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

Saved successfully!

Ooh no, something went wrong!