在Bash中的while循环中使用if语句

10

我有一些不同的结果保存在文件中:

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$
但是,当我尝试迭代它们并只打印名称时,我遇到了错误。 我只是不理解如何在“while循环”中使用“if”条件语句的基本原理。 最终,我想使用 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中引用你的正则表达式。 - Todd A. Jacobs
3个回答

10

你应该检查 > 而不是 <,对吧?

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

有时候在差异中,尖括号会反过来。通常表示 > 为添加,< 为删除。最终我想用 sed-substitute 将 '<' 替换为“已添加:$line”,将 '>' 替换为“已删除:$line”。 - capser

6

在这里您真的需要正则表达式吗?下面的shell通配符也可以起作用:

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

或者使用AWK:

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

1
“grep”将完成以下操作:
$ grep -oP '> \K\w+' <<END
18633a18634
> sashabrokerSTP
18634a18636
> sashatraderSTP
21545a21548
> yheemustr
END

sashabrokerSTP
sashatraderSTP
yheemustr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接