Tuesday, June 8, 2010

HOW TO READ LINES OF DATA IN A SHELL SCRIPT?

There's a very easy way to solve this:
while read myline
do
  echo $myline
done < inputfile
If the fields in a given line are separated by a known delimiter, either a tab or a comma, for example, then I suggest that you could use the cut command to extract specific values.
To demonstrate, let's pull some useful data out of the /etc/passwd file, a file that has lines of data in known fields, separated with a ":" as the deilmiter. Here's a typical line of data-
unknown:*:99:99:Unknown User:/var/empty:/usr/bin/false

The first field (remember, they're separated by colons) is the account name, the second the encrypted password (not shown because it's in a separate 'shadow' file for security), then the remaining fields are account ID, group ID, full user name, home directory and login shell.
Let's just pull out login and full name to see what that looks like:
#!/bin/sh

while read inputline
do
  login=`(echo $inputline | cut -d: -f1)`
  fulln=`(echo $inputline | cut -d: -f5)`
  echo login = $login and fullname = $fulln
done < /etc/passwd

exit 0
You can see how the cut program makes this a straightforward task, albeit one that can be done more quickly in other scripting languages like Perl. But if you want to work with shell scripts, the combination of a while read loop with the input redirected and the great cutcommand should give you all the data parsing capabilities you need.

No comments:

Post a Comment