[英]How to print specific rows of arrays using Bash?
I currently am working with a matrix in bash. 我目前正在使用bash中的矩阵。 I have, say, a 2x4 matrix inside a file:
我在文件中有一个2x4矩阵:
1 2 3 4
5 6 7 8
I have read from this file, and have stored all of these elements inside an array, such as: 我已从该文件中读取数据,并将所有这些元素存储在一个数组中,例如:
my_arr={1 2 3 4 5 6 7 8}
Next, I piped my echo output so that the spaces change to tabs: 接下来,通过管道传输回显输出,以便将空格更改为制表符:
echo ${my_arr[@]} | tr ' ' '\t'
**output**:
my_arr={1 2 3 4 5 6 7 8}
My question now is, I want to have a NEW-LINE after every four elements printed; 现在我的问题是,我希望每打印四个元素后就有一个NEW-LINE; in other words, is it possible for me to print out the array line-by-line, or row-by-row?
换句话说,我是否可以逐行或逐行打印数组?
EDIT Here is what I have in my actual code: 编辑这是我实际代码中的内容:
array=()
cols #This contains number of columns
while read line1 <&3
do
for i in $line1
do
array+=($i)
done
done 3<$2
#Now, array has all the desired values. I need to print them out.
Here is what is the desired output: 这是所需的输出:
1 2 3 4
5 6 7 8
Here is what is inside my array: 这是我数组中的内容:
(1 2 3 4 5 6 7 8)
Try this: 尝试这个:
printf '%s\t%s\t%s\t%s\n' "${my_arr[@]}"
The format string has four field specifiers (all %s
-- just plain strings) separated by \\t
(tab) and ending with \\n
(newline), it'll print the array elements four at a time in that format. 格式字符串有四个用
\\t
(制表符)分隔并以\\n
(换行符)结尾的字段说明符(所有%s
只是纯字符串),它将以该格式一次打印四个数组元素。
One possible (ugly) solution would be to store the size of the matrix in separate variables rows
and cols
. 一种可能的(丑陋的)解决方案是将矩阵的大小存储在单独的变量
rows
和cols
。 Please try the following: 请尝试以下操作:
set -f # prevent pathname expansion
array=()
rows=0
while read line1 <&3; do
vec=($line1) # split into elements
cols=${#vec[@]} # count of elements
array+=(${vec[@]})
rows=$((++rows)) # increment #rows
done 3<"$2"
# echo $rows $cols # will be: 2 and 4
ifs_back="$IFS" # back up IFS
IFS=$'\t' # set IFS to TAB
for ((i=0; i<rows; i++)); do
j=$((i * cols))
echo "${array[*]:$j:$cols}"
done
IFS="$ifs_back" # restore IFS
The output: 输出:
1 2 3 4
5 6 7 8
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.