由于您使用的是 Bash shell(请参阅您的标签),因此您可以使用 Bash 数组轻松访问输出字符串中的各个字段。比如像这样:
#!/bin/bash
# Your lines to gather the output:
# a=$(./algorithm < input.txt)
# b=$(./algorithm2 < input.txt)
# c=$(./algorithm3 < input.txt)
# Just to use your example output strings:
a="$(printf "12 13 315 \n 1 2 3 4 5 6 7 8 10 2 8 9 1 0 0 2 3 4 5")"
b="$(printf "2 3 712 \n 1 23 15 12 31 23 3 2 5 6 6 1 2 3 5 51 2 3 21")"
# Put the output in arrays.
a_array=($a)
b_array=($b)
# You can access the array elements individually.
# The array index starts from 0.
# (The names a1 and b1 for the third elements were your choice.)
a1="${a_array[2]}"
b1="${b_array[2]}"
# Print output strings.
# (The newlines in $a and $b are gobbled by echo, since they are not quoted.)
echo "Output a:" $a
echo "Output b:" $b
# Print third elements.
echo "3rd from a: $a1"
echo "3rd from b: $b1"
这个脚本输出
Output a: 12 13 315 1 2 3 4 5 6 7 8 10 2 8 9 1 0 0 2 3 4 5
Output b: 2 3 712 1 23 15 12 31 23 3 2 5 6 6 1 2 3 5 51 2 3 21
3rd from a: 315
3rd from b: 712
说明:
这里的技巧是 Bash 中的数组常量(文字)具有以下形式
(<space_separated_list_of_elements>)
例如
(1 2 3 4 a b c nearly_any_string 99)
任何分配了这样一个数组的变量,都会自动成为一个数组变量。在上面的脚本中,a_array=($a) 中发生的情况如下:Bash 将 $a 扩展为 <space_separated_list_of_elements> 并再次读取整个表达式,将其解释为数组常量。
此类数组中的单个元素可以像变量一样通过使用形式的表达式来引用
<array_name>[<idx>]
就像一个变量名。其中,<array_name> 是数组的名称,<idx> 是引用单个元素的整数。对于由数组常量表示的数组,索引从零开始连续计数元素。因此,在脚本中,${a_array[2]} 扩展为数组a_array 中的第三个元素。如果数组的元素更少,a_array[2] 将被视为未设置。
可以通过
分别输出数组
a_array中的所有元素,对应的索引数组,以及数组中的元素个数
echo "${a_array[@]}"
echo "${!a_array[@]}"
echo "${#a_array[@]}"
这些命令可用于追踪换行符的命运:鉴于上面的脚本,它仍在$a 中,如(观看引号)所示
echo "$a"
产生
12 13 315
1 2 3 4 5 6 7 8 10 2 8 9 1 0 0 2 3 4 5
但是换行符没有进入数组a_array。这是因为 Bash 将其视为分隔数组赋值中第三个和第四个元素的空格的一部分。如果换行符周围没有多余的空格,这同样适用,如下所示:
12 13 315\n1 2 3 4 5 6 7 8 10 2 8 9 1 0 0 2 3 4 5
我实际上假设你的 C 程序的输出是以这种形式出现的。