在Bash的'while'循环中使用'if'

cap*_*ser 5 bash loops if-statement while-loop

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

bash-3.00$ cat /tmp/voo
18633a18634
> sashabrokerSTP
18634a18636
> sashatraderSTP
21545a21548
> yheemustr
Run Code Online (Sandbox Code Playgroud)

我真的需要登录:

bash-3.00$ cat /tmp/voo | egrep ">|<"
> sashaSTP
> sasha
> yhee
bash-3.00$
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试迭代下摆并打印名称时,我会收到错误.我只是不明白使用"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$
Run Code Online (Sandbox Code Playgroud)

必须有一种循环文件然后对每一行做一些事情的方法.像这样:

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$
Run Code Online (Sandbox Code Playgroud)

Joh*_*ica 5

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

while read line; do
    if [[ $line =~ ">" ]]; then
        echo $line
    fi
done < /tmp/voo
Run Code Online (Sandbox Code Playgroud)


anu*_*ava 5

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

while read line; do [[ "$line" == ">"* ]] && echo "$line"; done < /tmp/voo
Run Code Online (Sandbox Code Playgroud)

或使用 AWK

awk '/^>/ { print "processing: " $0 }' /tmp/voo
Run Code Online (Sandbox Code Playgroud)