【问题标题】:Bash making loop to repeat code multiple timesBash 循环重复代码多次
【发布时间】:2017-08-29 11:39:35
【问题描述】:

我有一个名为 list_of_files.txt 的文件,其中包含 500 多个其他文件的列表。看起来是这样的:

list1.txt
list2.txt
list3.txt
etc

这个列表看起来像这样:(所有列都由数值组成) 值1 值2 值3 价值 4 价值 5 价值 6 等等

对于这些列表中的每一个,我想剪切某个感兴趣的列,对其进行排序以使数字按升序排列,并检查我的原始文件和新文件是否具有相同的顺序。

我尝试像这样制作一个循环 .sh 脚本:

for i in list_of_files.txt
do
cut -f3 -d " " list*.txt > chr*_all_positions.txt
sort -n chr*_all_positions.txt > chr*_ordered_positions.txt
diff chr*_all_positions.txt chr*_ordered_positions.txt > result_*.txt
done    

但是,这不起作用。任何帮助将不胜感激。

【问题讨论】:

    标签: bash loops


    【解决方案1】:

    遍历数字,而不是文件名:

    i=1
    while [[ -f list$i.txt ]] ; do
        cut -f3 -d " " list$i.txt > chr$i\_all_positions.txt
        sort -n chr$i\_all_positions.txt > chr$i\_ordered_positions.txt
        diff chr$i\_all_positions.txt chr$i\_ordered_positions.txt > result_$i.txt
        ((i++))
    done
    

    另外,您可以使用sort -csort -C 来检查输出是否已排序,而无需创建_ordered 文件。

    【讨论】:

    • 谢谢!这行得通。但是,如果我的列表文件是这样命名的:list1.1.txt、list1.2.txt 等,这段代码还能工作吗?我尝试时似乎没有。
    • 抱歉,我对 Bash 很陌生。我尝试通过编写 i=1.1 进行调整,但出现错误。
    • 我尝试使用 i=1.1 或 i=seq(1.1 1.2 1.3) 但这些都不起作用。据我了解,bash 似乎不喜欢在 while 循环中使用浮点数?
    • @m93:bash 不理解浮点数。使用 1.$i 或循环两个变量,如果需要转到 2.1、2.2、3.1 等,请使用 $i.$j
    【解决方案2】:

    使用 readarray 和数组

    readarray -t arrname < list_of_files.txt
    
    for filename in "${arrname[@]}"; do
        ...
    done
    

    使用内置读取

    while read filename; do
        ...
    done < list_of_files.txt
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      • 2014-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多