bash:Join多个变量的内容

bash: Join content of multiple variables

我有一个变量,其中包含几个其他变量的名称列表。这些变量每个都包含一个table。我想加入所有这些 table。

table 看起来像这样:

Name Average      Name Average
A 1               A 1.1
B 2               B 2.2
C 3               C 3.3                  etc.
D 4               D 4.4
E 5               E 5.5

我的变量名列表叫做 $all_variables,下面是它的内容(实际情况中有很多变量):

echo "$all_variables"

$table1
$table2
$table3
$table4
$table5

为了创建连接函数的参数列表,我创建了$all_variables_join,其中包含连接函数的参数:

echo "$all_variables_join"

<(echo "$table1") <(echo "$table2") <(echo "$table3") <(echo "$table4") <(echo "$table5")

然后我想运行加入(基于第一列,所以我使用默认选项)使用这样的东西:

join "$all_variables_join" > file.txt

将扩展到

join <(echo "$table1") <(echo "$table2") <(echo "$table3") <(echo "$table4") <(echo "$table5") > file.txt

而 file.txt 将包含如下内容:

Name Average      
A 1 1.1
B 2 2.2
C 3 3.3         etc...         
D 4 4.4
E 5 5.5

但是,当我尝试 运行 时,我得到了这个错误:

join "$all_variables_join" > file.txt

join: missing operand after `<(echo "$table1") <(echo "$table2") <(echo "table3") <(echo "$table4") <(echo "$table5")'
Try `join --help' for more information.

知道如何解决这个问题吗?

非常感谢任何帮助!

谢谢

编辑:修复了错误信息,我复制错了

@giles 和@ccarton 指出您需要去掉 $all_variables 周围的双引号。这是一个说明原因的示例:

touch 1
touch 2
x='1 2'
ls $x
ls "$x"

但是,这不会解决您的问题,因为正如@ccarton 所说,join 一次只接受两个文件。

一个可行的策略是创建一个包含所有可能名称(A、B、C...)的列:

table=$(echo -e "$table1\n$table2\n$table3\n$table4\n$table5" |
  tail -n+2 |
  awk '{print }' |
  sort -u)

然后加入每个 table 一个接一个:

table=$(join -a1 <(echo "$table") <(echo "$table1"))
table=$(join -a1 <(echo "$table") <(echo "$table2"))
table=$(join -a1 <(echo "$table") <(echo "$table3"))
table=$(join -a1 <(echo "$table") <(echo "$table4"))
table=$(join -a1 <(echo "$table") <(echo "$table5"))

可以使用循环而不是显式命名 table1...table5,但如果数据在文件而不是变量中,这样做是最自然的,例如,

mkdir /tmp/tables
echo "$table1" > /tmp/tables/table1
...
echo "$table5" > /tmp/tables/table1
for t in /tmp/tables/*; do
  table=$(join -a1 <(echo "$table") $f)
done

关于 join 的两个注意事项: 1. -a 保留该行,即使右侧没有匹配项 table。 2. 如果键还没有排序,则必须对其进行排序:

table=$(join -a1 <(echo "$table") <(sort -k1 $f))