LDP/LDP/guide/docbook/abs-guide/ex4.sh

41 lines
1.0 KiB
Bash
Raw Permalink Normal View History

2001-07-10 14:25:50 +00:00
#!/bin/bash
2008-07-20 23:16:47 +00:00
# subst.sh: a script that substitutes one pattern for
2004-01-05 13:20:57 +00:00
#+ another in a file,
2008-07-20 23:16:47 +00:00
#+ i.e., "sh subst.sh Smith Jones letter.txt".
# Jones replaces Smith.
2001-07-10 14:25:50 +00:00
2004-01-05 13:20:57 +00:00
ARGS=3 # Script requires 3 arguments.
2008-07-20 23:16:47 +00:00
E_BADARGS=85 # Wrong number of arguments passed to script.
2001-07-10 14:25:50 +00:00
if [ $# -ne "$ARGS" ]
then
echo "Usage: `basename $0` old-pattern new-pattern filename"
exit $E_BADARGS
fi
old_pattern=$1
new_pattern=$2
if [ -f "$3" ]
then
file_name=$3
else
echo "File \"$3\" does not exist."
exit $E_BADARGS
fi
2004-01-05 13:20:57 +00:00
# -----------------------------------------------
2008-07-20 23:16:47 +00:00
# Here is where the heavy work gets done.
2001-07-10 14:25:50 +00:00
sed -e "s/$old_pattern/$new_pattern/g" $file_name
2004-01-05 13:20:57 +00:00
# -----------------------------------------------
# 's' is, of course, the substitute command in sed,
#+ and /pattern/ invokes address matching.
2008-07-20 23:16:47 +00:00
# The 'g,' or global flag causes substitution for EVERY
2004-01-05 13:20:57 +00:00
#+ occurence of $old_pattern on each line, not just the first.
2008-07-20 23:16:47 +00:00
# Read the 'sed' docs for an in-depth explanation.
2001-07-10 14:25:50 +00:00
2008-11-23 22:43:47 +00:00
exit $? # Redirect the output of this script to write to a file.