2

我有一个文本文件标题“结果”,它包含

[  PASSED  ] 11 tests.
[  PASSED  ] 590 tests.
[  PASSED  ] 1231 tests.
[  FAILED  ] 4 tests.
[  FAILED  ] 500 tests.

我想添加 PASSED 测试并存储到变量中。添加 FAILED 测试,添加它们并存储到另一个变量中。

我怎样才能做到这一点?

4

4 回答 4

3

一种使用awk.

假设您的测试输出在一个名为的文件中test.out

#!/bin/bash
npasses=$(<test.out awk '
/ PASSED / { total += $4 }
END { print total }')

echo number of passing tests: $npasses

<test.out表示awk从 读取test.out

/ PASSED / { total += $4 }将第四个字段附加到一个名为 total 的变量中,但仅适用于与 regex 匹配的行PASSED

END { print total }在文件末尾运行,并打印存储在total.

于 2013-05-01T16:47:52.773 回答
1

如果日志在文件中,您可以使用

regex='\[ (PASSED|FAILED) \] (\d+) tests.'
while read -r line; do
    [[ $line =~ $regex ]] || continue
    count=${BASH_REMATCH[2]}
    case ${BASH_REMATCH[1]} in
        PASSED) let passed += count ;;
        FAILED) let failed += count ;;
    esac
done < input.txt

要直接从另一个进程读取,请将最后一行替换为

done < <( sourcecommand )

不要将 in 的输出通过管道sourcecommand传输到 while 循环;这将导致passedfailed在子shell中更新。

于 2013-05-01T16:50:05.423 回答
1

使用 bash 4 的关联数组:

declare -A total
while read _ result _ n _; do
    ((total[$result]+=$n))
done < results
for key in "${!total[@]}"; do
    printf "%s\t%d\n" "$key" ${total[$key]}
done
PASSED  1832
FAILED  504
于 2013-05-01T19:44:35.200 回答
0

从 Mikel 的答案扩展,您可以使用eval直接设置变量。

eval $(awk '/PASSED/ {pass += $4} /FAILED/ {fail += $4} END {print "pass="pass";fail="fail}' FILE_WITH_DATA)

您现在已经为您设置了变量。

echo $pass
echo $fail
于 2013-05-01T17:01:45.427 回答