【问题标题】:How to iterate two variables in bash script?如何在bash脚本中迭代两个变量?
【发布时间】:2020-10-22 04:25:11
【问题描述】:

我有这些文件:

file6543_015.bam
subreadset_15.xml
file6543_024.bam
subreadset_24.xml
file6543_027.bam
subreadset_27.xml

我想运行这样的东西:

for i in *bam && l in *xml
do
    my_script $i $l > output_file 
done 

因为在我的命令中,第一个 bam 文件与第一个 xml 文件一起出现。对于每个组合 bam/xml,该命令将给出一个特定的输出文件。

【问题讨论】:

  • 您的文件列表是否已修复?或者列表是如何生成的?
  • bam 和 xml 文件是通过之前完成的另一个命令生成的。它必须提供一个 .bam 文件及其 .xml 文件。
  • @Paillou :所以“其他”命令也建立了关联,哪个 bam 文件“属于”哪个 xml 文件?通常,这种关联在 bash 中由关联数组表示,但您没有显示 如何 其他命令生成两个文件列表。也许一个好的解决方案将涉及更改该命令。

标签: bash shell loops for-loop glob


【解决方案1】:

像这样,使用数组

bam=( *.bam )
xml=( *.xml )
for ((i=0; i<${#bam[@]}; i++)); do
    my_script "${bam[i]}" "${xml[i]}"
done

【讨论】:

    【解决方案2】:

    假设您有办法为每个特定输出唯一地命名您的 output_file, 这是一种方法:

    #!/bin/bash
    ls file*.bam | while read i
    do
        CMD=`echo -n "my_script $i "`
        CMD="$CMD `echo $i | sed -e 's/file.*_0/subreadset_/' -e 's/.bam/.xml/'`"
        $CMD >> output_file
    done
    

    【讨论】:

    • ls file*.bam | while read i 有问题。见Why you shouldn't parse the output of ls。除了那里讨论的问题之外,当使用 read 而不清除 IFS 并传递 -r 参数时,它会修剪尾随空格并删除反斜杠。
    • 除此之外,由于BashFAQ #50 中描述的原因,运行$CMD 无法按您预期的方式运行。特别是,它不适用于带有管道或引号的命令,因此此答案中给出的代码肯定无法按预期运行。 (由于BashFAQ #48 中描述的原因,can 将字符串解析为命令的机制通常容易出现安全问题,因此应始终使用 BashFAQ #50 实践。跨度>
    • 感谢 Charles 提供有用的反馈!
    猜你喜欢
    • 2010-11-17
    • 2010-09-20
    • 2016-09-18
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    • 2023-03-20
    • 2012-06-28
    • 1970-01-01
    相关资源
    最近更新 更多