Hack 88. Read data file fields inside a shell script

by Ramesh

This example shows how to read a particular field from a data-file and manipulate it inside a shell-script. For example, let us assume the employees.txt file is in the format of {employee-name}:{employee-id}:{department-name}, with colon delimited file as shown below.

$ cat employees.txt
Emma Thomas:100:Marketing
Alex Jason:200:Sales
Madison Randy:300:Product Development
Sanjay Gupta:400:Support
Nisha Singh:500:Sales

The following shell script explains how to read specific fields from this employee.txt file.

$ vi read-employees.sh
#!/bin/bash
IFS=:
echo "Employee Names:"
echo "---------------"
while read name empid dept
do
  echo "$name is part of $dept department"
done < ~/employees.txt

Assign execute privilege to the shell script and execute it.

$ chmod u+x read-employees.sh

$ ./read-employees.sh 
Employee Names:
---------------
Emma Thomas is part of Marketing department
Alex Jason is part of Sales department
Madison Randy is part of Product Development department
Sanjay Gupta is part of Support department
Nisha Singh is part of Sales department
1 sree December 30, 2010 at 9:09 pm

your program is nice but i wish to know how can we insert new record(i.e. another employee details) in to text file using shell script

2 Shah March 8, 2012 at 11:51 pm

Hi.
How to make output whem user key in staf code, the result shows the complete data about position, salary or name?Tq.

Comments on this entry are closed.

Previous post:

Next post: