代码之家  ›  专栏  ›  技术社区  ›  tstev

在unix中使用数组动态地将文件传递给命令

  •  2
  • tstev  · 技术社区  · 7 年前

    我有四份文件( file_one file_four ),这些文件的内容其实并不重要。我想将其中三个文件传递给一个命令(即 paste awk )按数组定义的特定顺序。 我的阵型是 order=(two one four) 是的。 我希望使用数组将所需的文件作为输入传递给命令,就像使用 * (即 paste file_* > combined_file )(二)

    paste file_${order[@]} > combined_file

    paste file_"${order[@]}" > combined_file

    paste file_"${order[*]}" > combined_file

    paste file_"{${order[@]}}" > combined_file

    paste file_{"${order[@]}"} > combined_file

    我看了不同的页面( 1 我是说, 2 我是说, 3 4 )但我不能让它工作。一个 loop 在这种情况下通过文件是行不通的 粘贴 锥子 是的。我想把文件一次全部传递给一个命令。视为我的 UNIX 知识有限,我可能误解了一些解决方案/答案。据我所知 this answer 阵列最初是如何在 bash 是的。

    预期结果: paste file_two file_one file_four > combined_file

    2 回复  |  直到 7 年前
        1
  •  2
  •   oliv    7 年前

    你可以用 printf 以下内容:

    paste $(printf "file_%s " ${order[@]}) > combined_file
    

    这样就避免了在 order 阵列。


    或者,使用bash ISM公司 ,您可以使用这个:

    paste ${order[@]/#/file_} > combined_file
    

    注意 # 与bash手册页中提到的模式开头匹配的:

    ${参数/模式/字符串}

    (…)如果模式以开头,则它必须 在参数的展开值的开头匹配。

        2
  •  1
  •   tstev    7 年前

    您可以在$()内使用for循环:

    paste $(for i in ${order[@]}; do echo file_$i; done) > output_file