You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用grep/sed/awk/perl保留git status中Untracked files以上内容?

提取git status中"Untracked files:"之前的内容

问题场景

执行git status得到如下输出:

git status
On branch a5
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   abc (new commits)

Untracked files:
  (use "git add <file>..." to include in what will be committed)
        058
        a.c
        ...

需要仅保留**"Untracked files:"**行以上的内容,可用以下几种命令实现:


用sed实现

直接匹配目标行后停止输出:

git status | sed '/^Untracked files:/q'

原理:/^Untracked files:/精准匹配以目标文本开头的行,q命令让sed匹配到后立即退出,只输出该行之前的所有内容。

用awk实现

匹配到目标行时退出,同时打印之前的所有行:

git status | awk '/^Untracked files:/{exit}1'

原理:/^Untracked files:/{exit}触发退出逻辑,1是awk的简写,代表执行print $0(打印当前行),直到退出前都会持续打印。

用grep实现

两种可行写法:

# 写法1:先获取目标行号再截取
git status | head -n $(git status | grep -n "^Untracked files:" | cut -d: -f1)

原理:先用grep -n拿到目标行的行号,再用head输出到该行为止的内容。

# 写法2:反向匹配目标行之前的内容
git status | grep -B 9999 "^Untracked files:" | grep -v "^Untracked files:"

原理:-B 9999获取目标行之前的所有内容(9999是足够大的数值,确保覆盖所有前置行),再用-v排除目标行本身。

用perl实现

逐行打印,匹配到目标行立即退出:

git status | perl -ne 'print; exit if /^Untracked files:/'

原理:-ne参数让perl逐行处理输入,先打印当前行,若匹配到目标行则直接退出。


内容的提问来源于stack exchange,提问作者Lewis Chan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 04:07:19