在Bash的'while'循环中使用'if' [英] Using 'if' within a 'while' loop in Bash

查看:192
本文介绍了在Bash的'while'循环中使用'if'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have thes diff results saved to a file:

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

我真的需要登录:

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

但是当我尝试迭代下摆并打印出来时名字我得到错误。
我只是不明白使用if和while循环的基本原理。
最后,我想在循环时使用,因为我想对这些行做一些事情 - 显然一次只加载一行到内存中,而不是一次加载整个文件。

But when I try to iterate through hem 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 while loop because I want to do something to the lines - and apparently while only loads one line into the memory at a time, as opposed to the whole file at once.

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 though 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$


推荐答案

您应该检查> ,而不是< ,没有?

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

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

这篇关于在Bash的'while'循环中使用'if'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆