I'd like to do the complement / opposite ofsed 13q;d <file.txtMore generally, is it possible to do this sort ofcomplement/inverse/opposite in sed? Or only for regexes?How do I print all but the third-to-last line?. Does thisrequire two tac's and counting forward in sed? Or is there a wayto get sed itself to count from the back?
How do I print all but the Nth to last line in sed?
text processing;sed;scripting
Part 1Simply delete the 13th line:sed '13d' <file.txtAnd a general way to do the complement of the above is:sed '13!d' <file.txtPart 2Because it can be done:sed -n ':a;${P;q};N;4,$D;ba' <file.txtNote the 4 is one more than the number you require.  So if you wanted the last-10th line, this would be 11.Testing with seq:$ seq 100 | sed -n ':a;${P;q};N;4,$D;ba'98$ Attempted explanation:a        # define label a${        # match the last line    P     # print the first line of the pattern space    q     # quit}N         # match all lines: append the next line to the pattern4,${      # match the range of lines 4 to the end of the file    D     # delete the first line of the pattern space}ba        # match all lines: jump back to label a Glenn Jackman's valuable addition:That was only the Nth line. Here is all BUT the Nth line:sed -n ':a;${s/^[^\n]*\n//;p;q};N;4,${P;D};ba'works with GNU sed, the \n sequence may not work with other seds.I tried this with BSD sed (OSX) and found it didn't quite work in the form above.  The issues appear to be:; used to separate lines seems to generally work, but doesn't work after a labelBSD sed appears to require ; after the last command in a one-line {} command group, whereas GNU sed does not\n can generally be used within the regular expression, but apparently not within a [] bracket expression.  So to exclude newlines, we can use something like [[:alnum:][:punct:][:graph:][:blank:]] instead, though this may exclude other characters (specifically other control characters).So this is an attempt at a more platform independent version:sed -n ':a${s/^[[:alnum:][:punct:][:graph:][:blank:]]*\n//p;q;};N;4,${P;D;};ba'This appears to work under OSX and Ubuntu.