Dave, where can I find a bash script that can read data from a file; the information should be separated by tabs or commas for easy pickup, and can only be accesed by a row.
This sounds suspiciously like a homework assignment, something I generally don’t offer assistance with since I think students should do their own work, but this particular question appears in my mailbox often enough that I thought it would be valuable to address it here.
There’s a very easy way to solve this:
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:
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:
while read inputline
login=”$(echo $inputline | cut -d: -f1)”
fulln=”$(echo $inputline | cut -d: -f4)”
echo login = $login and fullname = $fulln
done < /etc/passwd
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 cut command should give you all the data parsing capabilities you need.
Hope that helps you out with your homework. 🙂