我有一个命令行程序可以打印出如下的报告:
I found 0 problems on your database,
0 problems were found on your database
等等。
我想写一个linux shell脚本,只将数字输出到一个变量。我找不到正确的方法。我怀疑我没有正确使用grep
(或者有更好的命令);
即
I found 43 problems on your database,
43 problems were found on your database
$VAR=43
请告知
答案 0 :(得分:3)
$ var=$(echo -e "I found 43 problems on your database,
43 problems were found on your database" | grep -om 1 '[0-9]\+')
$ echo $var
43
答案 1 :(得分:1)
我发现Lev Levitsky的解决方案很完美,但我只是想补充一点,如果你的报告中包含很多带数字的行并且你想要处理它们中的每一行,你会使用类似的东西:
cat report | grep -o '[0-9]\+' | while read var
do
# do something with var
done