bash split string code example

Example 1: split string and create array bash

my_array=($(echo $string | tr "," "\n"))

Example 2: bash split string with awk

# Basic syntax:
awk '{split($column_to_split,array_name,"delimiter"); print a[index]}'
# Where:
#	- the array_name is usually shortened to a
#	- delimiter is the delimiter you want to split the string by
#	- index is the index of the string "piece" you want to work with

# Example usage:
# Say you want to split the following string by underscores and print
# the third item:
string_containing_CODE_to_pentagon
echo "string_containing_CODE_to_pentagon" | awk '{split($0,a,"_"); print a[3]}'
--> CODE

# Example usage:
# Say you have input_file.txt that contains two columns and you want to 
# split the second column by | and then by _ and then print the second 
# string of the final split:
cat file.txt
--> code_1	12|ab_cd|34_ef
	code_2	ef_56|gh_78_ij

awk '{split($2, a, "|");  split(a[2],b,"_"); print b[2]}' file.txt
--> cd
	78

Example 3: split string and create array bash

IFS=', ' read -r -a array <<< "$string"

Example 4: bash split string into variables

# separator is space
VAR="inforge srl bergamo"
read -r ONE TWO THREE <<< "${VAR}"
echo ${ONE}
echo ${TWO}
echo ${THREE}

# separator is comma
VAR="inforge,srl,bergamo"
IFS="," read -r ONE TWO THREE <<< "${VAR}"
echo "${ONE} ${TWO} ${THREE}"

Example 5: split bash string

IN="[email protected];[email protected]"
arrIN=(${IN//;/ })

Example 6: bash split variable by delimiter

IFS='|' read -r -a arrayName <<< "$variable"