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?
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?
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
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.)
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.
!
is still special inside single quotes in (t)csh, where that history expansion feature is from. See also How to use a special character as a normal one in Unix shells? – Stéphane Chazelas Aug 19 '22 at 11:51