Split String by Double Back Slashes in Bash

Viewed 58

I am trying to split the string by double back slashes in bash and somehow it's not working.

My string is as follow:

abc\\xyz

My Code:

my_str='abc\\xyz'
IFS='\\' read -r -a arr <<< "$my_str"
echo "${#arr[@]}"

I am expecting that the output would be '2' as the length of the array would be 2.

However, I get 3 as a result and when I try to print the array values, I only get 'abc', and the second index remains empty. It seems like something is wrong with my code but I am unable to identify it.

Can anyone please help to resolve the issue?

3 Answers

If there are no spaces in your string you could use bash pattern substitutions to replace pairs of backslashes by a space and assign the result to an indexed array:

$ my_str='abc\\xyz\uvw\\rst\\\012\\\\345'
$ declare -a arr=( ${my_str//\\\\/ } )
$ echo "${#arr[@]}"
5
$ printf '%s\n' "${arr[@]}"
abc
xyz\uvw
rst
\012
345

Perhaps you could try to replace the backslashes on the string fist as showcased in this previous question. However, this would be inefficient for very large strings.

A slightly different take -

$: my_str='abc\\123\\ghi\\\012\\jkl\\foo bar\\\\xyz'
$: IFS='|' read -r -a arr <<< "${my_str//\\\\/\|}"
$: printf "[%s]\n" "${arr[@]}"
[abc]
[123]
[ghi]
[\012]
[jkl]
[foo bar]
[]
[xyz]
Related