How to split a string in two substrings of same length using bash?

Using parameter expansion and shell arithmetic:

The first half of the variable will be:

${var:0:${#var}/2}

The second half of the variable will be:

${var:${#var}/2}

so you could use:

printf '%s\n' "${var:0:${#var}/2}" "${var:${#var}/2}"

You could also use the following awk command:

awk 'BEGIN{FS=""}{for(i=1;i<=NF/2;i++)printf $i}{printf "\n"}{for(i=NF/2+1;i<=NF;i++){printf $i}{printf "\n"}}'

$ echo abcdef | awk 'BEGIN{FS=""}{for(i=1;i<=NF/2;i++)printf $i}{printf "\n"}{for(i=NF/2+1;i<=NF;i++){printf $i}{printf "\n"}}'
abc
def

Using split, here strings and command substitution:

var=abcdef
printf '%s\n' "$(split -n1/2 <<<$var)" "$(split -n2/2 <<<$var)"

Another awk script can be:

echo abcdef | awk '{print substr($0,1,length/2); print substr($0,length/2+1)}'

Tags:

String

Bash