【问题标题】:Using 'if' within a 'while' loop in Bash在 Bash 的“while”循环中使用“if”
【发布时间】:2013-12-20 00:59:38
【问题描述】:

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

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 循环”一起使用的基础知识。 最终,我想使用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$

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

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$

【问题讨论】:

  • 不要在 Bash 4.x 中引用你的正则表达式。

标签: bash loops if-statement while-loop


【解决方案1】:

您应该检查&gt;,而不是&lt;,不是吗?

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

【讨论】:

  • 有时在差异上,尖括号会变向任何方向。通常表示 > 并添加和 ”的“
【解决方案2】:

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

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

或使用 AWK

awk '/^>/ { print "processing: " $0 }' /tmp/voo

【讨论】:

    【解决方案3】:

    grep 可以:

    $ grep -oP '> \K\w+' <<END
    18633a18634
    > sashabrokerSTP
    18634a18636
    > sashatraderSTP
    21545a21548
    > yheemustr
    END
    
    sashabrokerSTP
    sashatraderSTP
    yheemustr
    

    【讨论】:

      猜你喜欢
      • 2014-01-21
      • 2019-11-22
      • 1970-01-01
      • 2020-07-24
      • 2017-01-15
      • 2016-02-06
      • 1970-01-01
      • 2013-02-16
      • 2015-07-06
      相关资源
      最近更新 更多