简体   繁体   English

bash-在新行上输出每个数组元素

[英]bash - output each array element on new line

I am trying to create a TSV file from an array that I build inside a loop. 我试图从我在循环内构建的数组创建TSV文件。 I do get the values on each line to be tab separated, but I am not able to export each element of the array on a new line. 我确实将每一行的值都制表符分隔开,但是我无法在新行上导出数组的每个元素。 This is an example: 这是一个例子:

OUTPUT=()
#header
OUTPUT+=$(printf "col_1\tcol_2\tcol_3")

param_1="bla"
param_2="tra"
param_3="meh"

for i in 1 .. 3
  do
    OUTPUT+=$(printf "$param_1\t$param_2\t$param_3")
done
#export
printf '%s\n' "${OUTPUT[@]}" > test.tsv

I have also tried to put \\n at the end of each string that I insert in the array, but it did not work. 我还尝试将\\n放在要插入数组的每个字符串的末尾,但没有用。 Any idea what I am doing wrong? 知道我在做什么错吗? Thank you 谢谢

To append to an array you should use this syntax: 要追加到数组,应使用以下语法:

array+=(content)

Also there is no need to use printf for appending the static text. 同样,也不需要使用printf附加静态文本。

Here is a working script: 这是一个工作脚本:

OUTPUT=()
#header
OUTPUT+=("col_1\tcol_2\tcol_3")

param_1="bla"
param_2="tra"
param_3="meh"

for i in {1..3}
do
    OUTPUT+=("$param_1\t$param_2\t$param_3")
done
#export
printf '%b\n' "${OUTPUT[@]}" > test.tsv

Note use of %b in printf so that escape sequences are interpreted correctly. 请注意在printf使用%b ,以便正确解释转义序列。

Output: 输出:

cat test.tsv

col_1   col_2   col_3
bla     tra     meh
bla     tra     meh
bla     tra     meh

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

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