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.

t=${path_name%/*.*}<br />

# Same effect as t=`dirname $path_name`<br />

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

# These will fail in some cases, such as "../", "/foo////", # "foo/", "/".<br />

# Removing suffixes, especially when the basename has no suffix,<br />

#+ but the dirname does, also complicates matters.<br />

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

echo<br />

t=${path_name:11}<br />

echo "$path_name, with first 11 chars stripped off = $t"<br />

t=${path_name:11:5}<br />

echo "$path_name, with first 11 chars stripped off, length 5 = $t"<br />

echo<br />

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

t=${path_name/bozo/clown}<br />

echo "$path_name with \"bozo\" replaced by \"clown\" = $t"<br />

t=${path_name/today/}<br />

echo "$path_name with \"today\" deleted = $t"<br />

t=${path_name//o/O}<br />

echo "$path_name with all o's capitalized = $t"<br />

t=${path_name//o/}<br />

echo "$path_name with all o's deleted = $t"<br />

exit 0<br />

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

If prefix of var matches Pattern, then substitute Replacement for Pattern.<br />

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

If suffix of var matches Pattern, then substitute Replacement for Pattern.<br />

Example 9−19. Matching patterns at prefix or suffix of string<br />

#!/bin/bash<br />

# Pattern replacement at prefix / suffix of string.<br />

v0=abc1234zip1234abc<br />

echo "v0 = $v0"<br />

echo<br />

# Original variable.<br />

# abc1234zip1234abc<br />

# Match at prefix (beginning) of string.<br />

v1=${v0/#abc/ABCDEF} # abc1234zip1234abc<br />

# |−|<br />

echo "v1 = $v1"<br />

# ABCDE1234zip1234abc<br />

# |−−−|<br />

# Match at suffix (end) of string.<br />

v2=${v0/%abc/ABCDEF} # abc1234zip123abc<br />

# |−|<br />

echo "v2 = $v2"<br />

# abc1234zip1234ABCDEF<br />

# |−−−−|<br />

echo<br />

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

# Must match at beginning / end of string,<br />

#+ otherwise no replacement results.<br />

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

Chapter 9. Variables Revisited 91

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

Saved successfully!

Ooh no, something went wrong!