How to split a string on a delimiter in bash

Channel: Linux
Abstract: ' read -ra NAMES

We can use an internal field separator (IFS) variable to parse an array. Let’s use an example script, where first we define a string with colon-separated. Then we will use IFS to separate values based on a delimiter.

#!/usr/bin/env bash STR="orange:grapes:banana:apple" #String with names IFS=';' read -ra NAMES <<< "$STR" #Convert string to array #Print all names from array for i in "${NAMES[@]}"; do echo $i done123456789#!/usr/bin/env bash STR="orange:grapes:banana:apple"     #String with namesIFS=';' read -ra NAMES <<< "$STR"    #Convert string to array #Print all names from arrayfor i in "${NAMES[@]}"; do    echo $idone

Let’s execute this script and check for results.

./myscript.sh 
Output:
orange
grapes
banana
apple

Ref From: tecadmin
Channels: IFSbash

Related articles