使用sed解析%分数

使用sed解析%分数

我正在尝试解析我的 github ci 操作的代码覆盖率,我一切正常,但无法解析覆盖率%结果。请帮助我解析代码覆盖率的百分比分数,我无法让正则表达式工作:

命令

name: Pytest Coverage
on:
  pull_request:
    branches: [ main, dev ]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Set up Python 3.10
      uses: actions/setup-python@v2
      with:
        python-version: "3.10"
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install flake8 pytest pytest-cov
        if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
    - name: Build coverage file
      run: |
        pytest --cache-clear --cov=src tests/ > pytest-coverage.txt
    - name: Comment coverage
      uses: coroo/[email protected]
    - name: Get Coverage %
      run: |
        LAST_LINE=$(tail -4 pytest-coverage.txt)
        LAST_LINE=$(head -n 1 <<< "$LAST_LINE")
        echo "target line is $LAST_LINE"
        COVERAGE=$(sed -n '$s/.*?\([0-9]+\)%.*/\1/p' <<< "$LAST_LINE")
        echo "overall coverage is $COVERAGE"

$LAST_LINE 是

TOTAL                                               2401   1538    36%

$COVERAGE 当前为空,预期输出:

36%

答案1

使用sed

COVERAGE=$(sed 's/.*[[:space:]]\([0-9]\+%\)/\1/' <<< "$LAST_LINE")

答案2

删除所有内容,直到最后一个空白字符(空格或制表符):

$ sed 's/.*[[:blank:]]//' file
36%

用于awk打印最后一个空格分隔的字段:

$ awk '{ print $NF }' file
36%

或者,作为代码的一部分(假设只有一行以字符串开头TOTAL

COVERAGE=$( sed -n 's/^TOTAL.*[[:blank:]]//p' pytest-coverage.txt )

这直接从 中提取百分比pytest-coverage.txt,而无需调用heador tail

答案3

删除所有非空格字符加上空格字符直到最后:

echo "$LAST_LINE" | sed ':a s/^[^ ]* //;ta'

grep哪个知道o选项(例如gnu grep):

echo $LAST_LINE | grep -o '[0-9]*%'

相关内容