tags:

views:

252

answers:

3

I saw from

http://stackoverflow.com/questions/148451/how-to-use-sed-to-replace-only-the-first-occurrence-in-a-file

How to do most of what I want:

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

This finds the first match of something and extracts it (of course my real example is more complicated). I know sed as 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.

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

A: 

Sed usually has an option to specify more than one pattern to execute (IIRC, it's the -e option). That way, you can specify a second pattern that quits after the first line.

Another approach is to use sed to extract the first line (sed '1q'), then pipe that to a second sed command (what you show above).

Loadmaster
A: 

use gawk

gawk '/MATCH/{
            print "do something with "$0
            exit 
}' file
ghostdog74
A: 

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)).

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'

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...

nosatalian