How to Split a String into Two Substrings of Same Length Using Bash

bashstring

I would like to split a string into two halves and print them sequentially. For example:

abcdef

into

abc
def

Is there a simple way to do it, or it needs some string processing?

Best Answer

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
Related Question