如何使用 sed 从第一行返回匹配并提前退出的内容? [英] How to use sed to return something from first line which matches and quit early?

查看:58
本文介绍了如何使用 sed 从第一行返回匹配并提前退出的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了

如何使用sed 只替换文件中的第一次出现?

如何做我想做的大部分事情:

How to do most of what I want:

sed -n '0,/.*\(something\).*/s//\1/p'

这会找到某事物的第一个匹配项并提取它(当然我的真实示例更复杂).我知道 sed 有一个退出"命令,可以让它提前停止,但我不知道如何将q"与上面的行结合起来以获得我想要的行为.

This finds the first match of something and extracts it (of course my real example is more complicated). I know sed has a 'quit' command which will make it stop early, but I don't know how to combine the 'q' with the above line to get my desired behavior.

正如我在一些示例中看到的那样,我尝试将p"替换为 {p;q;},但这显然不起作用.

I've tried replacing the 'p' with {p;q;} as I've seen in some examples, but that is clearly not working.

推荐答案

我的具体用例是通过 'git log' 在 git-p4 导入的树上找出最后一次提交使用的 perforce 分支.git log (在没有 -n 的情况下调用时将记录每次发生的每次提交(对我来说是数十万)).

My specific use case was to find out via 'git log' on a git-p4 imported tree which perforce branch was used for the last commit. git log (when called without -n will log every commit that every happened (hundreds of thousands for me)).

我们不能先验地知道给 git '-n' 的值是什么.发布此内容后,我找到了我的解决方案:

We can't know a-priori what value to give git for '-n.' After posting this, I found my solution which was:

git log | sed -n '0,/.*\[git-p4:.*\/\/depot\/blah\/\([^\/]*\)\/.*/s//\1/p; /\[git-p4/ q' 

我仍然想知道如何使用非 '/' 分隔符执行此操作,而不必两次指定 'git-p4' 部分,一次用于提取,一次用于退出.必须有一种方法将两者结合在同一行...

I'd still like to know how to do this with a non '/' separator, and without having to specify the 'git-p4' part twice, once for the extraction and once for the quit. There has got to be a way to combine both on the same line...

这篇关于如何使用 sed 从第一行返回匹配并提前退出的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆