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 />

exit 0<br />

Variable expansion / Substring replacement<br />

These constructs have been adopted from ksh.<br />

${var:pos}<br />

Variable var expanded, starting from offset pos.<br />

${var:pos:len}<br />

Expansion to a max of len characters of variable var, from offset pos. See Example A−15 for an<br />

example of the creative use of this operator.<br />

${var/Pattern/Replacement}<br />

First match of Pattern, within var replaced with Replacement.<br />

If Replacement is omitted, then the first match of Pattern is replaced by nothing, that is,<br />

deleted.<br />

${var//Pattern/Replacement}<br />

Global replacement. All matches of Pattern, within var replaced with Replacement.<br />

As above, if Replacement is omitted, then all occurrences of Pattern are replaced by nothing,<br />

that is, deleted.<br />

Example 9−18. Using pattern matching to parse arbitrary strings<br />

#!/bin/bash<br />

var1=abcd−1234−defg<br />

echo "var1 = $var1"<br />

t=${var1#*−*}<br />

echo "var1 (with everything, up to and including first − stripped out) = $t"<br />

# t=${var1#*−} works just the same,<br />

#+ since # matches the shortest string,<br />

#+ and * matches everything preceding, including an empty string.<br />

# (Thanks, S. C. for pointing this out.)<br />

t=${var1##*−*}<br />

echo "If var1 contains a \"−\", returns empty string...<br />

var1 = $t"<br />

t=${var1%*−*}<br />

echo "var1 (with everything from the last − on stripped out) = $t"<br />

echo<br />

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

path_name=/home/bozo/ideas/thoughts.for.today<br />

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

echo "path_name = $path_name"<br />

t=${path_name##/*/}<br />

echo "path_name, stripped of prefixes = $t"<br />

# Same effect as t=`basename $path_name` in this particular case.<br />

# t=${path_name%/}; t=${t##*/} is a more general solution,<br />

#+ but still fails sometimes.<br />

# If $path_name ends with a newline, then `basename $path_name` will not work,<br />

#+ but the above expression will.<br />

# (Thanks, S.C.)<br />

Chapter 9. Variables Revisited 90

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

Saved successfully!

Ooh no, something went wrong!