首页 > 解决方案 > 使用数组将文件动态传递给 UNIX 中的命令

问题描述

我有四个文件(file_oneto 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

我查看了不同的页面(1234),但我无法让它工作。A通过文件在orloop的情况下不起作用。我想一次将所有文件传递给命令。鉴于我的知识有限,我可能误解了一些解决方案/答案。根据我从这个答案的理解,数组最初是如何开发的可能存在一些问题。pasteawkUNIXbash

期望的结果: paste file_two file_one file_four > combined_file

标签: arraysbashunix

解决方案


你可以使用printf

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

这避免了遍历order数组的所有元素。


或者,使用 bash ism,您可以使用:

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

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

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

(...) 如果 pattern 以 # 开头,它必须匹配参数扩展值的开头。


推荐阅读