Delete specific line number(s) from a text file using sed?

Viewed 332763

I want to delete one or more specific line numbers from a file. How would I do this using sed?

8 Answers

If you want to delete lines from 5 through 10 and line 12th:

sed -e '5,10d;12d' file

This will print the results to the screen. If you want to save the results to the same file:

sed -i.bak -e '5,10d;12d' file

This will store the unmodified file as file.bak, and delete the given lines.

Note: Line numbers start at 1. The first line of the file is 1, not 0.

and awk as well

awk 'NR!~/^(5|10|25)$/' file
$ cat foo
1
2
3
4
5
$ sed -e '2d;4d' foo
1
3
5
$ 

The shortest, deleting the first line in sed

sed -i '1d' file

As Brian states here, <address><command> is used, <address> is <1> and <command> <d>.

cat -b /etc/passwd | sed -E 's/^( )+(<line_number>)(\t)(.*)/--removed---/g;s/^( )+([0-9]+)(\t)//g'

cat -b -> print lines with numbers

s/^( )+(<line_number>)(\t)(.*)//g -> replace line number to null (remove line)

s/^( )+([0-9]+)(\t)//g #remove numbers the cat printed

Related