我有一个包含多个文件的目录
file1_1.txt
file1_2.txt
file2_1.txt
file2_2.txt
...
我需要运行这样的命令
command [args] file1 file2
所以我想知道是否有一种方法可以在所有文件上调用一次命令,而不是每次都在每对文件上调用它。
使用find
和xargs
,sort
,因为顺序在您的情况下似乎有意义:
find . -name 'file?_?.txt' | sort | xargs -n2 command [args]
如果您的command
可以在命令行上接受多对文件,那么运行
command ... *_[12].txt
扩展glob模式的文件(如*_[12].txt
)将自动排序,以便文件将正确配对。
如果command
只能接受一对文件,那么它将需要多次运行以处理所有文件。自动执行此操作的一种方法是:
for file1 in *_1.txt; do
file2=${file1%_1.txt}_2.txt
[[ -f $file2 ]] && echo command "$file1" "$file2"
done
- 您需要用正确的命令名和参数替换
echo command
。 - 参见移除字符串的一部分(BashFAQ/100(如何在bash中进行字符串操作?))来了解
${file1%_1.txt}
的解释。
#!/bin/bash
cmd (){
readarray -d " " arr <<<"$@"
for ((i=0; i<${#arr[@]}; i+=2))
do
n=$(($i+1))
firstFile="${arr[$i]}"
secondFile="${arr[$n]}"
echo "pair -- ${firstFile} ${secondFile}"
done
}
cmd file*_[12].txt
pair -- file1_1.txt file1_2.txt
pair -- file2_1.txt file2_2.txt