
# zsh split.sh
# or
# bash split.sh

string="go:python:rust:js"

split_by_tr() {
	echo "$string" | tr ":" "\n"
}

split_by_cut() {
	echo "$string" | cut -d ":" -f 1
	echo "$string" | cut -d ":" -f 2
	echo "$string" | cut -d ":" -f 3
	echo "$string" | cut -d ":" -f 4
}

split_by_awk() {
	# `$1=$1` is need，it tell awk to reformat the record
	echo "$string" | awk -F":" 'BEGIN {OFS="\n"} {$1=$1} {print $0}'
}

printf "\nsplit_by_tr:\n"
split_by_tr

printf "\nsplit_by_cut:\n"
split_by_cut

printf "\nsplit_by_awk:\n"
split_by_awk

split_by_IFS_read() {
	if [ -n "$ZSH_VERSION" ]; then
		# assume Zsh
		echo "zsh: $ZSH_VERSION"
		# zsh built-in command read
		IFS=":" read -rA aaa <<<"$string"
		for i in $aaa; do
			echo "$i"
		done

	elif [ -n "$BASH_VERSION" ]; then
		# assume Bash
		echo "bash: $BASH_VERSION"
		# /usr/bin/read
		IFS=":" read -ra aaa <<<"$string"
		for i in "${aaa[@]}"; do
			echo "$i"
		done

	else
		# assume something else
		echo "$string"
	fi

}

split_by_parameter_expansion() {
	# Parameter Expansion
	# https://zsh.sourceforge.io/Doc/Release/Expansion.html#Parameter-Expansion
	if [ -n "$ZSH_VERSION" ]; then
		# assume Zsh
		# 1. ${(s/:/)string}
		aaa=( ${(@s/:/)string} )
		# 2. or ${string//":"/" "}
		# aaa=( $(echo ${string//":"/" "}) )
		# 3. or read -rA
		# read -rA aaa <<< ${string//":"/" "}
		echo "zsh: $ZSH_VERSION"
		for i in "${aaa[@]}"; do
			echo "$i"
		done

	elif [ -n "$BASH_VERSION" ]; then
		# assume Bash
		# 1. read -ra
		read -ra aaa <<< "${string//:/ }"
		# 2. ${string//":"/" "}
		# aaa=( ${string//":"/" "} )
		echo "bash: $BASH_VERSION"
		for i in "${aaa[@]}"; do
			echo "$i"
		done

	else
		# assume something else
		echo "$string"
	fi
}

printf "\nsplit_by_IFS_read:\n"
split_by_IFS_read

printf "\nsplit_by_parameter_expansion:\n"
split_by_parameter_expansion
