简体   繁体   English

如何在同一行上打印bash数组

[英]How to print a bash array on the same line

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=$1
declare -a myArray

readarray myArray < $1

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会更好吗?

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

readarray retains the trailing newline in each array element. readarray在每个数组元素中保留尾部换行符。 To strip them, use the -t option. 要剥离它们,请使用-t选项。

readarray -t myArray < "$1"

One way : 单程 :

printf '%s\n' "${myArray[@]}" | paste -sd ' '

or simply : 或者干脆:

printf '%s ' "${myArray[*]}"

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[@]}

我最喜欢的技巧是

echo $(echo "${myArray[@]}")

@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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM