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
当前内容版权归 Ramesh Natarajan 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 Ramesh Natarajan .