Hack 88. Read data file fields inside a shell script

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
echo "Employee Names:"
echo "---------------"
while read name empid dept
  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

Comments on this entry are closed.

  • sree December 30, 2010, 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

  • Shah March 8, 2012, 11:51 pm

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