如何用一個換行符分隔字符串三行到三個變量?bash:將多行字符串讀入多個變量
# 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'和使用數組來代替不同的命名變量這樣的事情分配不同的變量。 –