[英]bash: read multi-line string into multiple variables
How can I assign a newline-separated string with eg three lines to three variables ?如何将一个以换行符分隔的字符串(例如三行)分配给三个变量?
# 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}"
I also tried using echo ${s} | read abc
我也试过使用
echo ${s} | read abc
echo ${s} | read abc
instead of <<<
, but couldn't get that to work either. echo ${s} | read abc
而不是<<<
,但也无法使其正常工作。
Can this be done in bash at all ?这可以在 bash 中完成吗?
read default input delimiter is \\n读取默认输入分隔符是\\n
{ read a; read b; read c;} <<< "${s}"
-d char : allows to specify another input delimiter -d char : 允许指定另一个输入分隔符
For example is there is no character SOH (1 ASCII) in input string例如,输入字符串中没有字符 SOH (1 ASCII)
IFS=$'\n' read -r -d$'\1' a b c <<< "${s}"
We set IFS
to $'\\n'
because IFS default value is :我们将
IFS
设置为$'\\n'
因为 IFS 默认值为:
$ printf "$IFS" | hd -c
00000000 20 09 0a | ..|
0000000 \t \n
0000003
EDIT: -d can take a null argument the space is mandatory between -d and null argument:编辑: -d 可以采用空参数 -d 和空参数之间的空格是强制性的:
IFS=$'\n' read -r -d '' a b c <<< "${s}"
The read
builtin documentation is available by typing help read
at the bash prompt.通过在 bash 提示符下键入
help read
可以获得read
内置文档。
EDIT: after comment about a solution for any number of lines编辑:在评论任意多行的解决方案之后
function read_n {
local i s n line
n=$1
s=$2
arr=()
for ((i=0;i<n;i+=1)); do
IFS= read -r line
arr[i]=$line
done <<< "${s}"
}
nl=$'\n'
read_n 10 "a${nl}b${nl}c${nl}d${nl}e${nl}f${nl}g${nl}h${nl}i${nl}j${nl}k${nl}l"
printf "'%s'\n" "${arr[@]}"
You are looking for the readarray
command, not read
.您正在寻找
readarray
命令,而不是read
。
readarray -t lines <<< "$s"
(Theoretically, $s
does not need to be quoted here. Unless you are using bash
4.4 or later, I would quote it anyway, due to some bugs in previous versions of bash
.) (理论上,这里不需要引用
$s
。除非您使用的是bash
4.4 或更高版本,否则我会引用它,因为bash
以前版本中存在一些错误。)
Once the lines are in an array, you can assign the separate variables if you need to一旦行在数组中,您可以根据需要分配单独的变量
a=${lines[0]}
b=${lines[1]}
c=${lines[2]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.