简体   繁体   English

如何在 bash 脚本中多次使用带有“-”(破折号)的标准输入?

[英]How to use more than once the stdin with a "-" (dash) in a bash script?

I'm writing a bash script whose input can be given through pipe, for this I use "-" but it can be used once.我正在编写一个 bash 脚本,其输入可以通过 pipe 给出,为此我使用“-”但它可以使用一次。 I tried to save it in a variable with input=$(cat -) but I am worried that if the input file is very large it may have problems.我试图用input=$(cat -)将它保存在一个变量中,但我担心如果输入文件非常大,它可能会出现问题。 I would like to know the best way to use the input that "-" gives me.我想知道使用“-”给我的输入的最佳方式。

The idea of the script is to do something like this:脚本的想法是做这样的事情:

#!/bin/bash
a=(cat - | grep -c "whatever")
b=(cat - | grep -c "whatever")
c=$(echo "($a+$b)" | bc)
echo "$c"

By default, cat reads its standard input.默认情况下, cat读取其标准输入。 So "-" is not needed.所以“-”是不需要的。

If you need to "grep" two regular expressions from the input, you can use grep without cat as it reads its standard input by default as well.如果您需要从输入中“grep”两个正则表达式,您可以使用不带catgrep ,因为默认情况下它也会读取其标准输入。

If the goal is to count the number of occurrences of two different patterns in the input, the equivalent of what you are trying to do could be something like:如果目标是计算输入中两种不同模式的出现次数,则相当于您尝试执行的操作可能类似于:

#!/bin/bash
grep -c -E '(whatever1|whatever2)'

As pointed out in the comments, if the requirement is also to take in account multiple occurrences of the patterns in the lines and both patterns in the same lines, the "-o" option of grep can be used:正如评论中所指出的,如果还需要考虑行中模式的多次出现以及同一行中的两种模式,则可以使用grep的“-o”选项:

-o, --only-matching -o,--仅匹配
Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line仅打印匹配行的匹配(非空)部分,每个这样的部分在单独的 output 行上

With such an option, the output of grep is as many lines as there are matching patterns.使用这样的选项,grep 的grep的行数与匹配模式的数量一样多。 So, the enhanced code counts those lines with wc -l and displays the result:因此,增强的代码使用wc -l计算这些行并显示结果:

#!/bin/bash
grep -o -E '(whatever1|whatever2)' | wc -l

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM