Advanced Bash-Scripting HOWTO: A guide to shell scripting, using Bash | ||
---|---|---|
Prev | Chapter 2. Starting Off With a Sha-Bang | Next |
A sed or awk script would normally be invoked from the command line by a sed -e 'commands' or awk -e 'commands'. Embedding such a script in a bash script permits calling it more simply, and makes it "reusable". This also permits combining the functionality of sed and awk, for example piping the output of a set of sed commands to awk. As a saved executable file, you can then repeatedly invoke it in its original form or modified, without retyping it on the command line.
Example 2-3. shell wrapper
#!/bin/bash # This is a simple script # that removes blank lines # from a file. # No argument checking. # Same as # sed -e '/^$/d $1' filename # invoked from the command line. sed -e /^$/d $1 # '^' is beginning of line, # '$' is end, # and 'd' is delete. |
Example 2-4. A slightly more complex shell wrapper
#!/bin/bash # "subst", a script that substitutes one pattern for # another in a file, # i.e., "subst Smith Jones letter.txt". if [ $# -ne 3 ] # Test number of arguments to script # (always a good idea). then echo "Usage: `basename $0` old-pattern new-pattern filename" exit 1 fi old_pattern=$1 new_pattern=$2 if [ -f $3 ] then file_name=$3 else echo "File \"$3\" does not exist." exit 2 fi # Here is where the heavy work gets done. sed -e "s/$old_pattern/$new_pattern/" $file_name # 's' is, of course, the substitute command in sed, # and /pattern/ invokes address matching. # Read the literature on 'sed' for a more # in-depth explanation. exit 0 # Successful invocation of the script returns 0. |
Exercise. Write a shell script that performs a simple task.
Закладки на сайте Проследить за страницей |
Created 1996-2024 by Maxim Chirkov Добавить, Поддержать, Вебмастеру |