【问题标题】:Iteratively pass one file from a collection of files as command line parameters in shell script从一组文件中迭代地传递一个文件作为 shell 脚本中的命令行参数
【发布时间】:2016-09-30 06:20:11
【问题描述】:

我有 x 个文件:A, B, C... 我需要做的是将这些文件中的每一个作为第一个命令行参数传递给 python文件并将其他文件作为第二个命令行参数传递,直到所有文件都作为 $1 传递一次。例如,在第一次迭代中,A 为 $1,B,C... 为 $2。在第二次迭代中,B 是 $1,A,C... 是 $2。我已经阅读了 shell 中的 shift 命令,但不太确定它是否适用于我的情况(我对 shell 脚本也比较陌生)。另外,我可以传递给我的 python 脚本的命令行参数的数量是否有限制?在遍历我的文件之前,我还想创建一个变量来保存文件名列表。谢谢!

【问题讨论】:

  • 参数的数量没有限制,但操作系统对所有参数的总长度有限制。

标签: bash shell file-io command-line-arguments


【解决方案1】:

Bash 有数组,并通过${array[@]:start:end} 语法支持数组切片,其中 startend 是可选索引。这足以完成工作。

#!/bin/bash

# Store the master list of file names in an array called $files.    
files=("$@")

for ((i = 0; i < ${#files[@]}; ++i)); do
    # Store the single item in $file and the rest in an array $others.
    file=${files[i]}
    others=("${files[@]:0:i}" "${files[@]:i+1}")

    # Run command.py. Use ${others[*]} to concatenate all the file names into one long
    # string, and override $IFS so they're joined with commas.
    (IFS=','; command.py "${files[i]}" "${others[*]}")
done

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多