我该如何将一个包含三行的字符串分配给三个变量?
我尝试使用
# test string
s='line 01
line 02
line 03'
# this doesn't seem to make any difference at all
IFS=$'\n'
# first naive attempt
read a b c <<< "${s}"
# this prints 'line 01||':
# everything after the first newline is dropped
echo "${a}|${b}|${c}"
# second attempt, remove quotes
read a b c <<< ${s}
# this prints 'line 01 line 02 line 03||':
# everything is assigned to the first variable
echo "${a}|${b}|${c}"
# third attempt, add -r
read -r a b c <<< ${s}
# this prints 'line 01 line 02 line 03||':
# -r switch doesn't seem to make a difference
echo "${a}|${b}|${c}"
# fourth attempt, re-add quotes
read -r a b c <<< "${s}"
# this prints 'line 01||':
# -r switch doesn't seem to make a difference
echo "${a}|${b}|${c}"
我尝试使用
echo ${s} | read a b c
替代 <<<
,但仍然无法使其运行。
这种操作在bash中是否可行?
mapfile
或readarray
,并使用数组而不是不同命名的变量来处理类似这样的事情。 - Eric Renouf