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 '${var1#$pattern1} =' "${var1#$pattern1}" # d12345abc6789<br />

# Shortest possible match, strips out first 3 characters abcd12345abc6789<br />

# ^^^^^ |−|<br />

echo '${var1##$pattern1} =' "${var1##$pattern1}" # 6789<br />

# Longest possible match, strips out first 12 characters abcd12345abc6789<br />

# ^^^^^ |−−−−−−−−−−|<br />

echo; echo<br />

pattern2=b*9<br />

# everything between 'b' and '9'<br />

echo "var1 = $var1" # Still abcd12345abc6789<br />

echo "pattern2 = $pattern2"<br />

echo<br />

echo '${var1%pattern2} =' "${var1%$pattern2}" # abcd12345a<br />

# Shortest possible match, strips out last 6 characters abcd12345abc6789<br />

# ^^^^ |−−−−|<br />

echo '${var1%%pattern2} =' "${var1%%$pattern2}" # a<br />

# Longest possible match, strips out last 12 characters abcd12345abc6789<br />

# ^^^^ |−−−−−−−−−−−−−|<br />

# Remember, # and ## work from the left end of string,<br />

# % and %% work from the right end.<br />

echo<br />

exit 0<br />

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

Example 9−17. Renaming file extensions:<br />

#!/bin/bash<br />

# rfe<br />

# −−−<br />

# Renaming file extensions.<br />

#<br />

# rfe old_extension new_extension<br />

#<br />

# Example:<br />

# To rename all *.gif files in working directory to *.jpg,<br />

# rfe gif jpg<br />

ARGS=2<br />

E_BADARGS=65<br />

if [ $# −ne "$ARGS" ]<br />

then<br />

echo "Usage: `basename $0` old_file_suffix new_file_suffix"<br />

exit $E_BADARGS<br />

fi<br />

for filename in *.$1<br />

# Traverse list of files ending with 1st argument.<br />

do<br />

mv $filename ${filename%$1}$2<br />

# Strip off part of filename matching 1st argument,<br />

#+ then append 2nd argument.<br />

done<br />

Chapter 9. Variables Revisited 89

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

Saved successfully!

Ooh no, something went wrong!