小能豆

How do I split a string on a delimiter in Bash?

shell

I have this string stored in a variable:

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

Now I would like to split the strings by ; 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.


After suggestions from the answers below, I ended up with the following which is what I was after:

#!/usr/bin/env bash

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

mails=$(echo $IN | tr ";" "\n")

for addr in $mails
do
    echo "> [$addr]"
done

Output:

> [bla@some.com]
> [john@home.com]

There was a solution involving setting Internal_field_separator (IFS) to ;. I am not sure what happened with that answer, how do you reset IFS back to default?

RE: IFS solution, I tried this and it works, I keep the old IFS and then restore it:

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

OIFS=$IFS
IFS=';'
mails2=$IN
for x in $mails2
do
    echo "> [$x]"
done

IFS=$OIFS

BTW, when I tried

mails2=($IN)

I only got the first string when printing it in loop, without brackets around $IN it works.


阅读 240

收藏
2023-12-26

共1个答案

小能豆

It looks like you’ve already found a solution using tr to replace ; with a newline. If you want to store the values in an array, you can do it like this:

#!/usr/bin/env bash

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

# Use IFS to split the string into an array
IFS=';' read -ra ADDR <<< "$IN"

# Print each element of the array
for addr in "${ADDR[@]}"; do
    echo "> [$addr]"
done

This script uses IFS to split the string into an array (ADDR). The loop then iterates over the array, and each element is printed.

Regarding your question about restoring IFS to its default value, you can store the original value before changing it and then restore it afterward:

#!/usr/bin/env bash

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

# Store the original value of IFS
OIFS=$IFS

# Set IFS to ;
IFS=';'

# Use IFS to split the string into an array
mails=($IN)

# Restore IFS to its original value
IFS=$OIFS

# Print each element of the array
for addr in "${mails[@]}"; do
    echo "> [$addr]"
done

In this example, OIFS is used to store the original value of IFS, and it’s restored after processing the string. This ensures that the change to IFS doesn’t affect other parts of your script.

2023-12-26