Bash Shell Read a Line Field By Field

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.

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post

How to Make Website WCAG Compliant?

Next Post

Link download Kali Linux 2020.1 (ISO + Torrent)

Related Posts