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/pytest-coverage-commentator@v1.0.2 - 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%
使用
sed
COVERAGE=$(sed 's/.*[[:space:]]\([0-9]\+%\)/\1/' <<< "$LAST_LINE")
刪除最後一個空白字元(空格或製表符)之前的所有內容:
$ 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
,而無需呼叫head
ortail
。