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.

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

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

  1. $ vi read-employees.sh
  2. #!/bin/bash
  3. IFS=:
  4. echo "Employee Names:"
  5. echo "---------------"
  6. while read name empid dept
  7. do
  8. echo "$name is part of $dept department"
  9. done < ~/employees.txt

Assign execute privilege to the shell script and execute it.

  1. $ chmod u+x read-employees.sh
  2.  
  3. $ ./read-employees.sh
  4. Employee Names:
  5. ---------------
  6. Emma Thomas is part of Marketing department
  7. Alex Jason is part of Sales department
  8. Madison Randy is part of Product Development department
  9. Sanjay Gupta is part of Support department
  10. Nisha Singh is part of Sales department