在 Bash 的“while”循环中使用“if”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20360151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:29:38  来源:igfitidea点击:

Using 'if' within a 'while' loop in Bash

bashloopsif-statementwhile-loop

提问by capser

I have these diff results saved to a file:

我将这些差异结果保存到文件中:

bash-3.00$ cat /tmp/voo
18633a18634
> sashabrokerSTP
18634a18636
> sashatraderSTP
21545a21548
> yheemustr

I just really need the logins:

我只需要登录:

bash-3.00$ cat /tmp/voo | egrep ">|<"
> sashaSTP
> sasha
> yhee
bash-3.00$

But when I try to iterate through them and just print the names I get errors. I just do not understand the fundamentals of using "if" with "while loops". Ultimately, I want to use the whileloop because I want to do something to the lines - and apparently whileonly loads one line into memory at a time, as opposed to the whole file at once.

但是当我尝试遍历它们并只打印名称时,我得到了错误。我只是不明白将“if”与“while循环”一起使用的基本原理。最终,我想使用while循环,因为我想对行做一些事情 - 显然一次while只将一行加载到内存中,而不是一次加载整个文件。

bash-3.00$ while read line; do  if [[ $line =~ "<" ]] ; then  echo $line ; fi ;  done <  /tmp/voo
bash-3.00$
bash-3.00$
bash-3.00$ while read line; do  if [[ egrep "<" $line ]] ; then  echo $line ; fi ;  done    <  /tmp/voo
bash: conditional binary operator expected
bash: syntax error near `"<"'
bash-3.00$
bash-3.00$ while read line; do  if [[ egrep ">|<" $line ]] ; then  echo $line ; fi ;  done <  /tmp/voo
bash: conditional binary operator expected
bash: syntax error near `|<"'
bash-3.00$

There has to be a way to loop through the file and then do something to each line. Like this:

必须有一种方法来遍历文件,然后对每一行做一些事情。像这样:

bash-3.00$ while read line; do  if [[ $line =~ ">" ]];
 then echo $line |  tr ">" "+" ;
 if [[ $line =~ "<" ]];
 then echo $line | tr "<" "-" ;
 fi ;
 fi ;
 done  < /tmp/voo


+ sashab
+ sashat
+ yhee
bash-3.00$

采纳答案by John Kugelman

You should be checking for >, not <, no?

你应该检查>,不是<,不是吗?

while read line; do
    if [[ $line =~ ">" ]]; then
        echo $line
    fi
done < /tmp/voo

回答by anubhava

Do you really need regex here? The following shell glob can also work:

你真的需要正则表达式吗?以下 shell glob 也可以工作:

while read line; do [[ "$line" == ">"* ]] && echo "$line"; done < /tmp/voo

OR use AWK:

或使用 AWK

awk '/^>/ { print "processing: " 
$ grep -oP '> \K\w+' <<END
18633a18634
> sashabrokerSTP
18634a18636
> sashatraderSTP
21545a21548
> yheemustr
END
}' /tmp/voo

回答by glenn Hymanman

grepwill do:

grep会做:

sashabrokerSTP
sashatraderSTP
yheemustr
##代码##