allenrabinovich
allenrabinovich

Reputation: 484

Using sed to output a file from first line and up to but not including a regular expression match

I'd like to use sed to collect the top section from a set of files and output the collected result to a digest file. What I am currently doing almost works:

for i in foo/*/bazz.txt; do sed '/regexp/ q' $i >> bazzdigest.txt; done

The problem is that the line that matches /regexp/ also gets included. I don't want to include it, so I have an extra-step of going into the file and removing it afterwards. Is there a way to do this so that that line does not get included?

Upvotes: 0

Views: 338

Answers (3)

speakr
speakr

Reputation: 4209

If you are using GNU sed, use Q instead of q:

for i in foo/*/bazz.txt; do sed '/regexp/ Q' $i >> bazzdigest.txt; done

This will output all lines before the match excluding the match itself.

Note that the Q command is a GNU extension.

Upvotes: 1

tvm
tvm

Reputation: 3449

Awk solution:

for i in foo/*/bazz.txt; do awk '/regexp/ {exit} {print}' "$i" >> bazzdigest.txt; done

Upvotes: 1

barsju
barsju

Reputation: 4446

Try this:

for i in foo/*/bazz.txt; do sed '/regexp/,$ d' $i >> bazzdigest.txt; done

It means from regexp to end, delete..

Upvotes: 3

Related Questions