3

What's the portable way to delete the first line1 from the pattern space ?
With gnu sed I can do

s/[^\n]*\n//

but as far as I know this (using \n in a bracket [] expression) is not portable.


Practical example: here, sed prints the last section of the file including the delimiter via portable code. I'd like to remove the first line from the pattern space so as to exclude the delimiter and do that in a portable manner. With gnu sed it's simple:

sed 'H;/===/h;$!d;//d;x;s/[^\n]*\n//' infile

1: Obviously this should be done without restarting the cycle of commands...

  • Indeed. POSIX sed only supports BREs (Basic Regular Expressions), and in BREs ”the special characters ., *, [, and `\\` […] shall lose their special meaning within a bracket expression.“ – myrdd Sep 10 '18 at 12:27
2

One way to portably do this sort of a thing is as follows:

sed -e '
   # ... assuming prev sed cmds made pattern space carry newline(s)
   y/\n_/_\n/     ;# exchange newlines with an underscore
   s/^[^_]*_//    ;# remove up till the first underscore, ummm newline
   y/\n_/_\n/     ;# revert the transformation
' 
2

I don't have a suitable sed to try, but you can always do interior loops testing for and removing characters until you get to the newline:

sed 'H
/===/h
$!d
//d
x
{
   :rpt
   s/^\n//
   t done
   s/.//
   t rpt
}
:done
'

The second test-branch, t rpt, needs to be a t rather than a b in order to reset the internal flag that says an s has suceeded since the last read. You don't need the {}, they are just to show the loop better.

1

Silly, but working:

sed 'h;G;s/\n/&&/;s/^\(.*\)\n\(.*\)\n\1\2$/\2/'

What's that? You double the whole content, then replace the first newline with two newlines. So you have the same content twice, with one additional newline after the first line. With backreferences you can now identify the different parts.

If you don't want to use the hold buffer:

sed 's/.*/&&/;s/\n/&&/;s/^\(.*\)\n\(.*\)\1\2$/\2/'

And no, I don't like that. If there is a way to avoid it, avoid it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.