The OpenNET Project / Index page

[ новости /+++ | форум | wiki | теги | ]

Поиск:  Каталог документации

2.2. Shell wrapper, self-executing script

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


# 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


# "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).
  echo "Usage: `basename $0` old-pattern new-pattern filename"
  exit 1


if [ -f $3 ]
    echo "File \"$3\" does not exist."
    exit 2

# 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.

Inferno Solutions
Hosting by

Закладки на сайте
Проследить за страницей
Created 1996-2022 by Maxim Chirkov
Добавить, Поддержать, Вебмастеру