在 Bash 中的单独行上打印数组元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15691942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Print array elements on separate lines in Bash?
提问by Axel Bregnsbo
How do I print the array element of a Bash array on separate lines? This one works, but surely there is a better way:
如何在单独的行上打印 Bash 数组的数组元素?这个有效,但肯定有更好的方法:
$ my_array=(one two three)
$ for i in ${my_array[@]}; do echo $i; done
one
two
three
Tried this one but it did not work:
试过这个,但没有用:
$ IFS=$'\n' echo ${my_array[*]}
one two three
回答by Gilles Quenot
Try doing this :
尝试这样做:
$ printf '%s\n' "${my_array[@]}"
The difference between $@
and $*
:
之间的差异$@
和$*
:
Unquoted, the results are unspecified. In Bash, both expand to separate args and then wordsplit and globbed.
Quoted,
"$@"
expands each element as a separate argument, while"$*"
expands to the args merged into one argument:"$1c$2c..."
(wherec
is the first char ofIFS
).
未引用,结果未指定。在 Bash 中,两者都扩展为单独的 args,然后进行分词和全局化。
引用,
"$@"
将每个元素扩展为单独的参数,而"$*"
扩展为合并为一个参数的 args:("$1c$2c..."
其中c
是 的第一个字符IFS
)。
You almost always want "$@"
. Same goes for "${arr[@]}"
.
你几乎总是想要"$@"
。也一样"${arr[@]}"
。
Always quote them!
总是引用它们!
回答by perreal
Just quote the argument to echo:
只需引用 echo 的参数:
( IFS=$'\n'; echo "${my_array[*]}" )
the sub shell helps restoring the IFS after use
子外壳有助于在使用后恢复 IFS
回答by Steven Penny
Using for:
使用为:
for each in "${alpha[@]}"
do
echo "$each"
done
Using history; note this will fail if your values contain !
:
使用历史;请注意,如果您的值包含!
以下内容,这将失败:
history -p "${alpha[@]}"
Using basename; note this will fail if your values contain /
:
使用basename; 请注意,如果您的值包含/
以下内容,这将失败:
basename -a "${alpha[@]}"
Using shuf; note that results might not come out in order:
使用shuf;请注意,结果可能不会按顺序出现:
shuf -e "${alpha[@]}"
回答by 0x00
Another useful variant is pipe to tr
:
另一个有用的变体是 pipe to tr
:
echo "${my_array[@]}" | tr ' ' '\n'
echo "${my_array[@]}" | tr ' ' '\n'
This looks simple and compact
这看起来简单而紧凑
回答by wuxmedia
I tried the answers here in a giant for...if loop, but didn't get any joy - so I did it like this, maybe messy but did the job:
我在一个巨大的 for...if 循环中尝试了这里的答案,但没有得到任何乐趣 - 所以我这样做了,也许很乱,但完成了工作:
# EXP_LIST2 is iterated
# imagine a for loop
EXP_LIST="List item"
EXP_LIST2="$EXP_LIST2 \n $EXP_LIST"
done
echo -e $EXP_LIST2
although that added a space to the list, which is fine - I wanted it indented a bit. Also presume the "\n" could be printed in the original $EP_LIST.
尽管这在列表中添加了一个空格,这很好 - 我希望它缩进一点。还假设可以在原始 $EP_LIST 中打印“\n”。