简体   繁体   English

Bash - for 循环中的多个条件

[英]Bash - Multiple conditions in a for loop

I'm trying to do a for loop with multiple conditions and I didn't find any information about how to do it on the web我正在尝试使用多个条件执行 for 循环,但我没有在网上找到有关如何执行此操作的任何信息

I'm sorry for the stupid questions, but I just started programming in linux我很抱歉这些愚蠢的问题,但我刚刚开始在 linux 中编程

what am I doing wrong here?我在这里做错了什么?

    #!/bin/bash

j=0

for line in `cat .temp_` || j in `seq 0 19`
do
    ...

done

the error says wrong syntax and that I can't use ||错误说语法错误,我不能使用 ||

Thanks a lot非常感谢

for line in `cat .temp_`
do
    if ! grep -Fxq $line $dictionary && [ $j -lt 20 ]
    then
        echo $line >> $dictionary
        j=$((j+1))
    fi
    [ $j -gt 20 ] && break
done

You can't check a condition in a for loop in shell. 您无法在shell中的for循环中检查条件。 You must do it in a extra statement. 您必须另外声明。 In this case so: 在这种情况下:

[ $j -gt 20 ] && break

Another solution, without break : 另一种解决方案,无需break

while read line && [ $j -lt 20 ]
do
    if ! grep -Fxq $line $dictionary && [ $j -lt 20 ]
    then
        echo $line >> $dictionary
        j=$((j+1))
    fi
done < .temp_

You are trying to combine two different styles of for -loops into one. 您正在尝试将两种不同样式的for -loops组合为一种。 Instead, just break if the value of j becomes too large: 相反,如果j的值太大,就中断:

j=0
while read -r line; do
    [[ j >= 20 ]] && break
    ...
done < ._temp

(This, by the way, is the preferred way to iterate over a file in bash. Using a for -loop runs into problems if the file is too large, as you essentially building a command line using the entire contents of the file.) (顺便说一下,这是在bash中迭代文件的首选方法。如果文件太大,则使用for -loop会出现问题,因为实际上是使用文件的全部内容来构建命令行。)

[UPDATE: the following is based on my conjecture as to the purpose of the loop. [更新:以下内容基于我对循环目的的猜测。 See Calculate Word occurrences from file in bash for the real context.] 有关实际上下文,请参见在bash中从文件计算Word出现次数 。]

Actually, you can dispense with the loop. 实际上,您可以省去循环。 You are looking for at most 20 lines from .temp_ that do not already appear in the file whose name is in dictionary, right? 您正在从.temp_寻找最多20行,这些行尚未出现在名称在字典中的文件中,对吗?

sort -u .temp_ | grep -f $dictionary -Fx -v -m 20 >> $dictionary

This will call grep just once, instead of once per line in .temp_ . 这将只调用grep一次,而不是.temp_每行一次。

A simple nested for-loop? 一个简单的嵌套for循环?

for line in `cat file`; do for j in {0..19}; do
     your_commands
done; done

If I understand you correctly (you want to run a command on every line 20 times). 如果我理解正确(您想在每行上运行命令20次)。

Once I need to process all files inside a directory, but only until nth file or until all is processed:一旦我需要处理目录中的所有文件,但只处理第 n 个文件或处理完所有文件:

count=1
nth=10
for f in folder/*; do
  ((count++))
  # process $f
  if [[ $count -gt $nth ]] 
  then
    break
  fi
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM