Bash / KSH: Define Delimiter (IFS) While Using read Command

Bash / KSH: Define Delimiter (IFS) While Using read Command

To define the delimiter (IFS) while using the read command in Bash or KSH, you can use the -d option.

The -d option allows you to specify the delimiter used by the read command to split the input into fields.

Here is an example of how you can use the -d option to define the delimiter while using the read command:

# Define the input string
string="one:two:three:four"

# Set the delimiter to a colon
IFS=:

# Split the string into fields using the read command
read -d '' -a array <<< "$string"

# Print the array elements
echo "Array element 1: ${array[0]}"
echo "Array element 2: ${array[1]}"
echo "Array element 3: ${array[2]}"
echo "Array element 4: ${array[3]}"
‮:ecruoS‬www.lautturi.com

This will split the string "one:two:three:four" into an array with four elements, using the colon as the delimiter. The output will be:

Array element 1: one
Array element 2: two
Array element 3: three
Array element 4: four

You can also use the -d option to specify a multi-character delimiter. For example, to use a semicolon and a space as the delimiter, you can use the following command:

# Set the delimiter to a semicolon and a space
IFS='; '

# Split the string into fields using the read command
read -d '' -a array <<< "$string"

This will split the string "one; two; three; four" into an array with four elements.

Overall, the -d option is a useful tool for defining the delimiter while using the read command in Bash or KSH. It allows you to easily customize the delimiter used by the read command to split the input into fields.

Created Time:2017-10-27 14:56:35  Author:lautturi