1
pattern="::a::b::"
oldIFS=$IFS
IFS="::"
read -r -a extractees <<< $pattern
IFS=$oldIFS

this results in

{"a","b"}

however, I need to maintain the indices, so I want

{"","a","b",""}

(for comparison, if I wanted {"a","b"}, I would have written "a::b".

Why? because these elements are later split again (on a different delimiter) and the empty "" values should result in an empty list then.

How do I achieve this?

1
  • @Cyrus {"","a","b",""} - as I have written in the post itself. {"","a","","b",""} makes no sense if :: is the delimiter and it changes the indices. Commented Oct 31, 2016 at 19:30

1 Answer 1

1

No field separator can be longer than 1 character, unfortunately, so '::' → ':'.

Aside of that, globbing should be explicitly turned off to prevent potential filename expansion in an unquoted variable.

set -f # disable globbing
pattern=":a:b c:"
oldIFS=$IFS
IFS=":"
extractees=($pattern)
IFS=$oldIFS

echo "'${extractees[0]}'"
echo "'${extractees[1]}'"
echo "'${extractees[2]}'"
echo "'${extractees[3]}'"
Sign up to request clarification or add additional context in comments.

4 Comments

Unquoted parameter expansions are also not a reliable way to split a string into an array.
@chepner okay. $IFS is already set, so the only thing that can affect unquoted expansion is filename globbing. However, it does not occur here; just tried on BASH 4.3. Don`t know what the exact reason is, this case is seemingly undocumented. But to be on the safe side, globbing can always be explicitly disabled via set -f. Edited.
@chepner consecutive whitespace characters are removed only if $IFS equals its default value. Prooflink.
Ah, right. Definitely mention that globbing should be turned off, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.