since the default value of the IFS variable is a newline/tab/space, the following code:
while read -r line
do
echo $line
done <<< "hello\nworld"
Run Code Online (Sandbox Code Playgroud)
outputs:
hello
world
Run Code Online (Sandbox Code Playgroud)
so this code:
while IFS=',' read -r part
do
echo $part
done <<< "hello,world"
Run Code Online (Sandbox Code Playgroud)
but this one just outputs:
hello,world
Run Code Online (Sandbox Code Playgroud)
and I expected it to print the same as the script from before.
what am I missing here?
IFS is a field separator, not a record separator. (The default record separator is the newline; it can be changed with the -d argument to read). Each call to read reads a single record, and optionally splits it into multiple variables at field boundaries.
When you run read -r part, you're reading only one record (the one that goes into part), so there's no separating to be done: it's thus normal and expected that $part contains the entire record, commas included.
By contrast, if you used -a to specify your destination as an array (read -r -a parts) or passed more than one destination variable (read -r part1 part2 part3), splitting into fields would take place.
Compare to:
while IFS=, read -r key value; do
echo "key=$key, value=$value"
done <<EOF
hello,world
hi,neighbor
EOF
Run Code Online (Sandbox Code Playgroud)
Similarly, one can read a line into an array:
while IFS=, read -r -a parts; do # split on comma into array
printf 'Read %d parts: ' "${#parts[@]}" # count items in array
printf '<%s> ' "${parts[@]}" # print those items in arrow brackets
printf '\n'
done <<EOF
three,word,array
this,is,four,words
EOF
Run Code Online (Sandbox Code Playgroud)
...which, as expected, emits:
Read 3 parts: <three> <word> <array>
Read 4 parts: <this> <is> <four> <words>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1387 次 |
| 最近记录: |