Splitting strings in Bash
Inspired by how split a string in bash? and BASH: Split a string without 'cut' or 'awk'.
function split() { declare DELIM printstr reststr str if [[ "${1}" == '-d' ]] && [[ $# -ge 2 ]]; then DELIM="${2}" shift 2 else DELIM=" " fi # if /dev/stdin has a size greater than zero ... if [[ -s /dev/stdin ]]; then str="$(</dev/stdin)" else str="${@}" fi while [[ -n "$str" ]]; do reststr="${str#*${DELIM}}" [[ "${str}" == "${reststr}" ]] && printf "%s\n" "${str}" && return 0 #[[ "${str}" == "${reststr}" ]] && printf "%s\n" "${str}" && break #[[ "${str}" == "${reststr}" ]] && printf "%s\n" "${str}" && str="" && continue printstr="${str%%${DELIM}*}" [[ -n "${printstr}" ]] && printf "%s\n" "${printstr}" str="${reststr}" done return 0 } split -d a bdsdaaadfeeee echo bdsdaaadfeeee | split -d a split -d a " bd sdaaadfe eee " echo " bd sdaaadfe eee " | split -d a split -d aa " bd sdaaadfe eee " echo " bd sdaaadfe eee " | split -d aa split -d aaa " bd sdaaadfe eee " echo " bd sdaaadfe eee " | split -d aaa #---------------------------------------------------------------------- function split0() { declare DELIM printstr reststr str if [[ "${1}" == '-d' ]] && [[ $# -ge 2 ]]; then DELIM="${2}" shift 2 else DELIM=" " fi # if /dev/stdin has a size greater than zero ... if [[ -s /dev/stdin ]]; then str="$(</dev/stdin)" else str="${@}" fi while [[ -n "$str" ]]; do reststr="${str#*${DELIM}}" [[ "${str}" == "${reststr}" ]] && printf "%s\000" "${str}" && return 0 #[[ "${str}" == "${reststr}" ]] && printf "%s\000" "${str}" && break #[[ "${str}" == "${reststr}" ]] && printf "%s\000" "${str}" && str="" && continue printstr="${str%%${DELIM}*}" [[ -n "${printstr}" ]] && printf "%s\000" "${printstr}" str="${reststr}" done return 0 } split0 -d a bdsdaaadfeeee | xargs -0 split0 -d a bdsdaaadfeeee | xargs -0 echo split0 -d a bdsdaaadfeeee | xargs -0 printf "%s\n" echo bdsdaaadfeeee | split0 -d a | xargs -0 split0 -d a " bd sdaaadfe eee " | xargs -0 printf "%s\n" echo " bd sdaaadfe eee " | split0 -d a | xargs -0 printf "%s\n" split0 -d aa " bd sdaaadfe eee " | xargs -0 printf "%s\n" echo " bd sdaaadfe eee " | split0 -d aa | xargs -0 printf "%s\n" split0 -d aaa " bd sdaaadfe eee " | xargs -0 printf "%s\n" echo " bd sdaaadfe eee " | split0 -d aaa | xargs -0 printf "%s\n"