如何在同一行打印 bash 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39985683/
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
How to print a bash array on the same line
提问by Alec Beyer
I am reading in filetype data into a bash array and need to print its contents out on the same line with spaces.
我正在将文件类型数据读入 bash 数组,并且需要将其内容打印在带有空格的同一行上。
#!/bin/bash
filename=
declare -a myArray
readarray myArray <
echo "${myArray[@]}"
I try this and even with the echo -n flag it still prints on newlines, what am I missing, would printf work better?
我尝试了这个,即使使用 echo -n 标志它仍然在换行符上打印,我错过了什么, printf 会更好地工作吗?
采纳答案by chepner
readarray
retains the trailing newline in each array element. To strip them, use the -t
option.
readarray
保留每个数组元素中的尾随换行符。要剥离它们,请使用该-t
选项。
readarray -t myArray < ""
回答by DarckBlezzer
Simple way to print in one line
一行打印的简单方法
echo "${myArray[*]}"
example:
例子:
myArray=(
one
two
three
four
[5]=five
)
echo "${myArray[*]}"
#Result
one two three four five
回答by Gilles Quenot
One way :
单程 :
printf '%s\n' "${myArray[@]}" | paste -sd ' '
or simply :
或者干脆:
printf '%s ' "${myArray[*]}"
回答by Arindam Roychowdhury
In case you have the array elements coming from input, this is how you can
如果您有来自输入的数组元素,您可以这样做
- create an array
- add elements to it
- then print the array in a single line
- 创建一个数组
- 给它添加元素
- 然后在一行中打印数组
The script:
剧本:
#!/usr/bin/env bash
declare -a array
var=0
while read line
do
array[var]=$line
var=$((var+1))
done
# At this point, the user would enter text. EOF by itself ends entry.
echo ${array[@]}
回答by user1699917
My favourite trick is
我最喜欢的技巧是
echo $(echo "${myArray[@]}")
echo $(echo "${myArray[@]}")
回答by Buoy
@sorontar's solution posted in a comment was handy:
@sorontar 在评论中发布的解决方案很方便:
printf '%s ' "${myArray[@]}"
but in some places the leading space was unacceptable so I implemented this
但在某些地方领先的空间是不可接受的所以我实现了这个
local str
printf -v str ' %s' "${myArray[@]}" # save to variable str without printing
printf '%s' "${str:1}" # to remove the leading space