img

Bash Shell Read a Line Field By Field

September 8, 2019

How do I read a file field-by-field under UNIX / Linux / BSD Bash shell? My sample input data file is as follows:

device1,deviceType,major,minor,permissions
device2,deviceType,major,minor,permissions

….
.
deviceN,deviceTypeN,major,minor,permissions

For each line I need to construct and execute a shell command as follows:
/path/to/deviceMaker --context=$1 -m $permissions $device2 $deviceType $major $minor

You can use a while loop along with the read command, Internal Field Separator (IFS), and HERE STRINGS as follows:

#!/bin/bash
input=/path/to/data.txt
[ $# -eq 0 ] && { echo "Usage: $0 arg1"; exit 1; }
arg="$1"
cmd=/path/to/deviceMaker
while read -r line
do
	IFS=, read -r f1 f2 f3 f4 f5 <<<"$line"
        # quote fields if needed 
	$cmd --context="$arg" -m $f5 $f1 $f2 $f3 $f4
done <"$input"

See also

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Article Tags:
Article Categories:
How To

Comments are closed.