|
August
4, 2003 -
Using set to Process Unknown/Varying
Numbers of Fields
|
It's
relatively simple to write a shell script
that will handle records or variables when
the number of fields is known or fixed,
but how would you write code to process
records and variables when this number is unknown or varies from record to
record? This week's tip will provide
you with one option for accomplishing this
task.
Consider the following excerpt of shell
script code:
|
<previous
code>
set $RECORD
while [ $1 ]
do
<field
processing code>
shift
done
<subsequent code>
|
The first line
of actual code ("set $RECORD")
will assign each field of the record
stored in the variable RECORD to a
positional parameter (e.g. $1, $2, $3,
etc.). These fields are typically
delimited with a blank space, but not
always.
Next, the while statement checks the value
of $1 to decide whether or not the
commands within the loop should be
executed. If the value of $1 is
null, processing will continue at the
statement immediately following the loop's
closing statement ("done").
Located within the while loop are field
processing statements, and the shift
command. shift will move (or
"shift") the values in the
positional parameters to the left, or
down, one position. This means that
the value in $1 will be discarded, the
value in $2 will be assigned to $1, the
value to $3 will be assigned to $2, and so
on.
After shift is executed, the value in $1
is checked again for a null value.
The loop will continue until all of the
record's fields have been processed.
Since the code is only concerned about the
value stored in $1, the number of total
fields in each record is really
irrelevant.
If multiple records are being processed
(e.g. read individually from an external
file), it's safe to assume that this
snippet of code will be enclosed within another
loop that stores each record in the
RECORD variable.
|
|
Learn
more...
If you are new to the UNIX or Linux
operating system and would like to learn
more, you may want to consider
registering for LiveFire Labs' UNIX
and Linux Operating System Fundamentals
online training course.
If you already have a solid grasp of the
fundamentals but would like to learn more
about the Korn shell and basic and
advanced shell scripting, taking our Korn
Shell Scripting course will be
beneficial to you.
Our innovative hands-on training model
allows you to learn
UNIX by completing hands-on
exercises on real servers in our Internet
Lab.
More
Tips...
· Popular
UNIX Tips from the Past
|
|
|
|
 |
 |
|
Receive
the UNIX Tip, Trick, or Shell Script of the
Week by Email
|
|
|