【问题标题】:How to parse a report using Shell script?如何使用 Shell 脚本解析报告?
【发布时间】:2012-06-19 16:31:54
【问题描述】:

我有一个命令行程序,可以打印出如下报告:

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

请指教

【问题讨论】:

  • 你的输出是 2 行还是很多行?
  • 学习使用和组合awkgrep,也许还有一些脚本语言,如pythonocamlrubyperl

标签: linux shell scripting sed awk


【解决方案1】:
$ 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

【讨论】:

  • 酷!现在:有时它给我“我发现 X blah blah blah [newline] 问题 [newline] 问题 [etc.] x 问题是 foud。我想从最后一行而不是第一行获取数字。有没有办法这样做?
  • @user1461638 尝试将grep -om 1 '[0-9]\+' 更改为grep -o '[0-9]\+' | tail -1
  • 非常感谢!这非常有用
  • @user1461638 很高兴为您提供帮助。如果解决了您的问题,请考虑 accepting the helpful answer
【解决方案2】:

我发现 Lev Levitsky 的解决方案非常完美,但我只想补充一点,如果您的报告包含许多带有数字的此类行并且您想要处理每一行,您将使用以下内容:

cat report | grep -o '[0-9]\+' | while read var
do
  # do something with var
done

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-23
    • 2014-12-08
    • 1970-01-01
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多