delete lines containing a text

Remove every line of a file that contains a word, or keep only those lines.

  • text
  • files

Steps

  1. grep -v 'text' file.txt > new.txt

    write the file without those lines to a new file

  2. sed -i '/text/d' file.txt

    delete them in the file itself

  3. sed -i.bak '/text/d' file.txt

    the same, keeping the old file as file.txt.bak

  4. grep 'text' file.txt

    the opposite: show only the lines that contain it

  5. grep -c 'text' file.txt

    count how many lines contain it

Notes

  • macOS: sed -i '' '/text/d' file.txt (its sed needs a value after -i).

Commands used

  • grep
  • sed

Each has a page in lore: lore grep opens it.