Bash Shell Read a Line Field By Field

In Bash shell, you can use the read command to read input line by line, and then use the IFS (Internal Field Separator) variable to specify the delimiter character(s) that separate the fields.

Here is an example script that reads input from a file called data.txt and extracts the fields delimited by commas:

#!/bin/bash

# Set the input file
input_file="data.txt"

# Set the delimiter character
IFS=','

# Read the input line by line
while read field1 field2 field3
do
# Print each field on a separate line
echo "Field 1: $field1"
echo "Field 2: $field2"
echo "Field 3: $field3"
done < "$input_file"

In this example, the IFS variable is set to a comma character, so the read command will split each line of input at commas and assign the resulting fields to the variables field1, field2, and field3.

The while loop reads input line by line from the file specified in the < redirection operator, and the echo command prints each field on a separate line.

When you run this script, it will read the data from the data.txt file, split each line at commas, and print the fields for each line.

You can modify the delimiter character(s) by changing the value of the IFS variable to a different set of characters, such as a tab or a space.

Leave a Comment