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호출하지 않고 직접 백분율을 추출합니다 .headtail

답변3

공백이 아닌 모든 문자와 공백 문자를 끝까지 제거합니다.

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

grep옵션을 알고 있는 사람 o(예 gnu grep: ):

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

관련 정보