How can I split a string by a delimiter in Bash, storing elements as variables or array elements?

How do I split a string on a delimiter in Bash? I have a string stored in a variable:

IN="bla@some.com;john@home.com"

I would like to split the string by the “;” delimiter so that I have:

ADDR1="bla@some.com"
ADDR2="john@home.com"

I don’t necessarily need the ADDR1 and ADDR2 variables. If they are elements of an array, that’s even better.

Hiii Kusha,

You can use the Internal Field Separator (IFS) variable to split a string into an array in Bash. Here’s how you can do it:

# Set the input string
IN="bla@some.com;john@home.com"

# Set the IFS to ;
IFS=';' read -ra ADDR <<< "$IN"

# Iterate over the array elements
for i in "${ADDR[@]}"; do
  # process "$i"
  echo "$i"
done

This will split the string by the “;” delimiter and store the parts in the ADDR array. You can then iterate over the array elements and process them as needed.

Hey Kusha,

You can use parameter expansion to split a string into an array in Bash. Here’s an example:

# Set the input string
IN="bla@some.com;john@home.com"

# Replace ';' with ' ' and store the result in an array
arrIN=(${IN//;/ })

# Access elements of the array
echo ${arrIN[1]}  # Output: john@home.com

This approach replaces all occurrences of ‘;’ in the string with a space, then interprets the space-delimited string as an array. It’s a concise way to split a string into an array in Bash.

Hey Kusha,

The cut command is indeed quite useful for parsing delimited text, especially in scenarios like log file processing. Here’s how you can use cut to split a string based on a delimiter:

# Split the string and extract the first field
echo "bla@some.com;john@home.com" | cut -d ";" -f 1

# Split the string and extract the second field
echo "bla@some.com;john@home.com" | cut -d ";" -f 2

In the first command, cut uses ; as the delimiter (-d ";") and extracts the first field (-f 1), giving you bla@some.com. Similarly, the second command extracts the second field (-f 2), giving you john@home.com.

This approach can be extended to process entire files with rows of delimited text. For example, if you have a log file with entries like 2015-04-27|12345|some action|an attribute|meta data, you can use cut in a loop to extract specific fields for further processing.

# Assuming each line in the log file follows the format 'date|id|action|attribute|metadata'
cat logfile.txt | while IFS='|' read -r date id action attribute metadata; do
    # Process each field as needed
    echo "Date: $date, ID: $id, Action: $action, Attribute: $attribute, Metadata: $metadata"
done

In this example, cut is used with the -d option to specify the delimiter as |, and -f is used to extract specific fields from each line.