bash - 将多行 var 回显到 Grep

标签 bash variables grep

如何通过管道将多行变量传递给 grep 并保留换行符?

预期结果:

$ git status --porcelain --branch
## test-branch
M  image.go
 M item.go
?? addme.go
?? testdata/
$ git status --porcelain --branch | grep -c '^??'
2

答案是“2”。

但是在脚本中(或者只是输入命令),我无法从下面解析这个 $x

$ x="$(git status --porcelain --branch)"
$ y="$(echo $x | grep -c '^??')"
$ echo "$y"
0

我怀疑这与我在 y 变量赋值中回显 $(echo $x ... 的方式有关。

编辑:我只执行 x="$(git status --porcelain --branch)" 一次,并使用多个 grep 解析它几十次> 用于各种输出、值、计数、状态、分支、后面、前面和其他值的命令。因此,我需要将 git status ... 的输出分配给一个变量,并多次解析它。

最佳答案

如果您不引用 $x,它将进行分词,并且 echo 将打印一长行。您只需要使用 "$x":

x=$(git status --porcelain --branch)
y=$(echo "$x" | grep -c '^??')
echo "$y"

此外,您不必使用额外的 echo:

y=$(grep -c '^??' <<< "$x")

我建议使用shellcheck 。在这种情况下这确实很有帮助。

关于bash - 将多行 var 回显到 Grep,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47744539/

相关文章:

Windows Batch - 检查一个命令变量是否出现在另一个命令变量中

grep - 需要对多个字符串的第一次出现进行 grep

unix - grep -f 最大模式数?

linux - 读取变量直到输出大于 BASH 中的某个值

c++ - 许多变量的数据交换

linux - 使用 awk 和 bash 监视 exec 输出到日志

PHP 通过引用传递问题

linux - Ubuntu: service --status-all 不能与 |更多或 | grep git

linux - 使用 bash 脚本输入 ssh 密码,没有那个文件或目录

bash:在预定义位置拆分二进制文件