[英]Bash - Multiple conditions in a for loop
我正在嘗試使用多個條件執行 for 循環,但我沒有在網上找到有關如何執行此操作的任何信息
我很抱歉這些愚蠢的問題,但我剛剛開始在 linux 中編程
我在這里做錯了什么?
#!/bin/bash
j=0
for line in `cat .temp_` || j in `seq 0 19`
do
...
done
錯誤說語法錯誤,我不能使用 ||
非常感謝
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
您無法在shell中的for
循環中檢查條件。 您必須另外聲明。 在這種情況下:
[ $j -gt 20 ] && 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_
您正在嘗試將兩種不同樣式的for
-loops組合為一種。 相反,如果j
的值太大,就中斷:
j=0
while read -r line; do
[[ j >= 20 ]] && break
...
done < ._temp
(順便說一下,這是在bash中迭代文件的首選方法。如果文件太大,則使用for
-loop會出現問題,因為實際上是使用文件的全部內容來構建命令行。)
[更新:以下內容基於我對循環目的的猜測。 有關實際上下文,請參見在bash中從文件計算Word出現次數 。]
實際上,您可以省去循環。 您正在從.temp_尋找最多20行,這些行尚未出現在名稱在字典中的文件中,對嗎?
sort -u .temp_ | grep -f $dictionary -Fx -v -m 20 >> $dictionary
這將只調用grep
一次,而不是.temp_
每行一次。
一個簡單的嵌套for循環?
for line in `cat file`; do for j in {0..19}; do
your_commands
done; done
如果我理解正確(您想在每行上運行命令20次)。
一旦我需要處理目錄中的所有文件,但只處理第 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.