0

I have a file like:

A
B
C
D
E
F

I can get line 2 to 4 using sed -n 2,4p

How can get all the lines except 2 to 4?

Jim L.
  • 7,997
  • 1
  • 13
  • 27
Ahmad Ismail
  • 2,678

4 Answers4

4

Your sample command is indeed the inverse of what you want. Read the man page and note that -n disables sed's default behaviour, which is to print each line that is processed. You disable the printing of lines, and then explicitly print only lines in the range 2,4.

One solution would be to enable the default printing of lines, but tell sed to delete lines within your range:

$ sed 2,4d << EOF
> A
B
C
D
E
F
> EOF
A
E
F
Jim L.
  • 7,997
  • 1
  • 13
  • 27
3

A function can be preceded by a ! character, in which case the function shall be applied if the addresses do not select the pattern space.

(source)

In your case the function is p and the addresses are 2,4.

sed -n '2,4!p'

(Single quotes in case ! is special in your shell.)

1

IMHO awk syntax is simpler as it's just basic math:

$ awk '(2 <= NR) && (NR <= 4)' file
B
C
D

$ awk '(NR < 2) || (4 < NR)' file
A
E
F

You CAN write range expressions in awk like you have to in sed but you don't HAVE to in awk so it's best not to for clarity maintainability, etc.

Ed Morton
  • 31,617
0
awk '!(NR>=2 && NR<=4)' filename

output

A
E
F