Home > front end >  match newline just inserted via sed
match newline just inserted via sed

Time:09-30

I'm running GNU sed (and I don't care about BSD compatibility for now) with multiple expressions: one expression inserts a newline, and another one should do something, honouring these newly added lines.

E.g.

$ cat lines
a time and a place.
sing a good song

$ cat lines  | sed -e 's|\ba\b|\n&|g' -e '/^[^a]/d'

now I would expect sed to insert a newline just before every a-word, and then remove all non-empty lines that do not start with a, giving me:


a time and 
a place
a good song

This is indeed what I get if run my expressions in two separate seds, like sed -e 's|\ba\b|\n&|g' | sed -e '/^[^a]/d.

However, when running this in a single sed instance, I instead get nothing:

$ cat lines  | sed -e 's|\ba\b|\n&|g' -e '/^[^a]/d'
$

I'm a bit baffled.

obviously, sed does not add new lines, but instead inserts the newline character in the existing lines. subsequent expressions only see the pre-determined lines (as fed into sed).

Is there a way to have sed create true lines that it can use in subsequent expressions (within the same process)?

CodePudding user response:

This might work for you (GNU sed):

sed 's/\<a\>/\n&/g;/\n/!d;s/^[^\n]*\n//' file

Insert a newline before all as, delete any line that doesn't contain at least one a and then delete up to and including the first newline.

N.B. Sed presents each line (minus its newline) in the pattern space. To see the pattern space as sed sees it, you can invoke the l0 command which will send the pattern space to stdout.

  • Related