[英]nested bash loop to print two arrays on same line
Hi I have created two arrays: 嗨,我创建了两个数组:
$ echo "${prot}"
abc
def
ghi
$ echo "${pos}"
123
456
789
where element n in prot refers to element n in pos. 其中prot中的元素n表示pos中的元素n。 so I want to print the corresponding elements on one line, with one new line per pair. 所以我想在一行上打印相应的元素,每对一行换一行。
I am trying to do this with a nested loop, where I split the respective arrays into elements via a newline: 我试图通过嵌套循环做到这一点,在这里我通过换行符将各个数组拆分为元素:
for i in "${!prot[@]}"; do
for j in "${!pos[@]}"; do
IFS=$'\n' read -a arr1 <<<"$i"
IFS=$'\n' read -a arr2 <<<"$j"
echo $i $j
done
done
but this only gives me the last pair. 但这只给了我最后一对。 it's one line which is great, but it's not printing them all. 这是一条很棒的线,但并不是全部打印出来。 what am I doing wrong? 我究竟做错了什么?
Expected output: 预期产量:
$
abc 123
def 456
ghi 789
I created the arrays in the first place by doing 我首先通过创建数组
for i in *.fasta; do
IFS=_-. read -ra arr <<<"$i"
tmp=$(printf "${arr[*]: 0: 1} ${arr[*]: 1: 1} ${arr[*]: -2: 1}")
fa+="$tmp\n"
done
for i in "${fa[@]}"; do
prot=$(echo -e "$i" | cut -d\ -f 1)
pos=$(echo -e "$i" | cut -d\ -f 2)
done
First you have to split strings into proper bash arrays: 首先,您必须将字符串拆分为适当的bash数组:
readarray -t prot_array <<< "$prot"
readarray -t pos_array <<< "$pos"
Then, I would try something like: 然后,我会尝试类似的方法:
for ((i=0; i<${#prot_array[@]}; i++)); do
echo "${prot_array[i]} ${pos_array[i]}";
done
It's simple solution without nested loops. 这是没有嵌套循环的简单解决方案。 ${#prot[@]}
is the size of the array. ${#prot[@]}
是数组的大小。 The loop displays corresponding elements of both arrays. 循环显示两个数组的对应元素。
Another way that works even when dealing with arrays of differing length is simply to use a while
loop with a counter variable to output the arrays side-by-side so long as both arrays have values: 即使处理不同长度的数组,另一种可行的方法是简单地使用带有计数器变量的while
循环并排输出数组,只要两个数组都有值即可:
#!/bin/bash
a1=( 1 2 3 4 5 )
a2=( a b c d e f g )
declare -i i=0
while [ "${a1[i]}" -a "${a2[i]}" ]; do
printf " %s %s\n" "${a1[i]}" "${a2[i]}"
((i++))
done
exit 0
Output 产量
$ bash arrays_out.sh
1 a
2 b
3 c
4 d
5 e
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.