How do I split a string on a delimiter in Bash?
Taken from Bash shell script split array:
IN="[email protected];[email protected]"
arrIN=(${IN//;/ })
echo ${arrIN[1]} # Output: [email protected]
Explanation:
This construction replaces all occurrences of ';'
(the initial //
means global replace) in the string IN
with ' '
(a single space), then interprets the space-delimited string as an array (that's what the surrounding parentheses do).
The syntax used inside of the curly braces to replace each ';'
character with a ' '
character is called Parameter Expansion.
There are some common gotchas:
- If the original string has spaces, you will need to use IFS:
IFS=':'; arrIN=($IN); unset IFS;
- If the original string has spaces and the delimiter is a new line, you can set IFS with:
IFS=$'\n'; arrIN=($IN); unset IFS;
You can set the internal field separator (IFS) variable, and then let it parse into an array. When this happens in a command, then the assignment to IFS
only takes place to that single command's environment (to read
). It then parses the input according to the IFS
variable value into an array, which we can then iterate over.
This example will parse one line of items separated by ;
, pushing it into an array:
IFS=';' read -ra ADDR <<< "$IN"
for i in "${ADDR[@]}"; do
# process "$i"
done
This other example is for processing the whole content of $IN
, each time one line of input separated by ;
:
while IFS=';' read -ra ADDR; do
for i in "${ADDR[@]}"; do
# process "$i"
done
done <<< "$IN"