Delete Lines Matching a Pattern or Line Number with ‘sed’

I had a unique situation where I wanted to remove a line that contained “PRINT” in a batch of HTML pages. To do it quickly, I used the sed command:

sed -i '/PRINT/d' *.htm

The -i option tells sed to edit the file in place so I wouldn’t have to play pipe games. The '/PRINT/d' argument tells sed to look for the text PRINT and then delete the line that contains it. Keep in mind that this will work on the entire document, not only the first item it finds. So, be sure this is what you want. Test the waters first, especially if you’re working with a batch job where this is going to edit many files at once.

Another possibility was to delete only the particular line number that this pattern occurred on:

# First, use grep to find the line it occurs on
grep -n "PRINT" *.html
# Then, use sed to delete that particular line (ie. line 16)
sed -i '16 d'

There are a lot more sed tricks here, so be sure to check it out.

Feel free to donate if this post prevented any headaches! Another way to show your appreciation is to take a gander at these relative ads that you may be interested in:

There's 0 Comment So Far

Share your thoughts, leave a comment!