BASH printf 数组在最后一个条目上带有字段分隔符和换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26304266/
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
BASH printf array with field separator and newline on last entry
提问by Geraint Anderson
How can I print out an array in BASH with a field separator between each value and a newline at the end.
如何在 BASH 中打印出一个数组,每个值之间有一个字段分隔符,最后有一个换行符。
The closest I can get with a single printf is printf '%s|' "${arr1[@]}"
where | is the field separator. The problem with this is there is no line break at the end. Any combination of \n I try to put in there either puts in a line break on every entry or none at all!
我可以用一个 printf 得到的最接近的printf '%s|' "${arr1[@]}"
地方是 | 是字段分隔符。问题是最后没有换行符。我尝试放入的 \n 的任何组合要么在每个条目上放置一个换行符,要么根本没有!
Is there a way of doing it on one line or do I need to use printf '%s|' "${arr1[@]}";printf "\n"
有没有办法在一行上完成或者我需要使用 printf '%s|' "${arr1[@]}";printf "\n"
Thanks,
谢谢,
Geraint
杰兰特
回答by Charles Duffy
Yes, you need two commands for this. printf '%s|' "${array[@]}"; echo
is perfectly conventional.
是的,为此您需要两个命令。printf '%s|' "${array[@]}"; echo
是完全传统的。
Alternately, if you don't want the trailing |
, you can temporarily modify IFS
to use your chosen separator as its first character, and use "${array[*]}"
:
或者,如果您不想要尾随|
,您可以临时修改IFS
以使用您选择的分隔符作为其第一个字符,并使用"${array[*]}"
:
IFS="|$IFS"; printf '%s\n' "${array[*]}"; IFS="${IFS:1}"
回答by I-GaLaXy-I
If you don't want to have the |
be printed, you could also remove it and just put in a space or whatever seperator you want to use (e.g. , or -):
如果您不想|
打印,您也可以将其删除并放入一个空格或您想要使用的任何分隔符(例如,或 -):
printf '%s ' "${arr1[@]}" ; printf '\n'
printf '%s ' "${arr1[@]}" ; printf '\n'
If you need this more often you should use a function, due to writing the same code over and over is not the best way:
如果你更频繁地需要这个,你应该使用一个函数,因为一遍又一遍地编写相同的代码并不是最好的方法:
print_array ()
{
# run through array and print each entry:
local array
array=("$@")
for i in "${array[@]}" ; do
printf '%s ' "$i"
done
# print a new line
printf '\n'
}
usage:
用法:
print_array "${array_name[@]}"
example:
例子:
array01=(one two three)
print_array "${array01[@]}"
echo "this should be a new line"
output:
输出:
one two three
this should be a new line