如何通过管道将多行变量传递给 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/