If I want to read a string and split it on a given delimiter, I can set IFS
and store string slices in an array. Then I can do whatever I want with its items:
while IFS=_ read -r -a myarray; do
printf "%s -\n" "${myarray[@]}"
done <<< "a_b"
This returns:
$ while IFS=_ read -r -a myarray; do echo "hello"; printf "%s -\n" "${myarray[@]}"; done <<< "a_b"
hello
a -
b -
However, I sometimes want to read just one of these fields per loop. So I wonder if there is a way to have this while
loop be fed by a slice every time. That is, on the first iteration have read
get just a
, on the second one just b
and so on.
I found a way changing the way we feed the loop: instead <<< "a_b"
I use tr
to split this up by replacing every _
with a new line with < <(tr "_" "\n" <<<"a_b")
:
$ while IFS=_ read -r -a myarray; do echo "hello"; printf "%s -\n" "${myarray[@]}"; done < <(tr "_" "\n" <<<"a_b")
hello
a -
hello
b -
However, I wonder: is there any other way for this? As we have IFS
to change the field separators, does Bash have any other variable to set the "record separators" like awk
for example has?