I've a list of urls of which some point to images:


How do I remove those lines from the file?

4 Answers 4

cat file | grep -v "\.png" >new_file_without_pngs

Updated for comment:

egrep -iv "\.(png|jpg|jpeg|gif|etc)" file >new_file
  • no inline option? I'd like to get rid of ".png" and ".jpg" for that matter. Also case-insenstive?
    – simpatico
    Aug 26, 2011 at 4:00
  • I would add a $ at end, just in case.
    – enzotib
    Aug 26, 2011 at 7:47

For the in-place editing variant, you can use sed like the following:

$ sed -i -r 's/.*\.(png|jpg).*//I' file

It will remove the lines containing either .png or .jpg directly in the file. The -i option passed to sed means 'in-place editing'. Make a backup of your file before executing this command, or try it first without the -i option if you are unsure.

The I flag is to perform a case-insensitive matching.

  • 5
    How about using the sed delete command 'd': sed -i -r '/\.(png|jpg)$/I d' file
    – frielp
    Aug 26, 2011 at 8:16
  • 3
    you can add an extension to -i so that it will create a backup file: sed -i .bak -r 's/.*\.(png|jpg).*//I' file
    – Julian
    Aug 26, 2011 at 9:08
  • 3
    +1 to the "use d" comment: using s/.*blah.*// will leave blank lines, it won't delete lines. Aug 26, 2011 at 10:23

You can use Vim in Ex mode:

ex -sc 'g/\.png/d' -cx file
  1. g global search

  2. d delete

  3. x save and close


If you have sponge you can swap out the contents of a file in place like this:

grep -E -iv "\.(png|jpg|jpeg|gif)" file | sponge file

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .