delete lines containing a text
Remove every line of a file that contains a word, or keep only those lines.
Steps
-
grep -v 'text' file.txt > new.txtwrite the file without those lines to a new file
-
sed -i '/text/d' file.txtdelete them in the file itself
-
sed -i.bak '/text/d' file.txtthe same, keeping the old file as file.txt.bak
-
grep 'text' file.txtthe opposite: show only the lines that contain it
-
grep -c 'text' file.txtcount how many lines contain it
Notes
- macOS:
sed -i '' '/text/d' file.txt(its sed needs a value after -i).
Commands used
grepsed
Each has a page in lore: lore grep opens it.
Related recipes
- compare two foldersFind which files differ between two folders, or are only in one of them.
- count lines, words and filesCount the lines of a file or of a command's output, the words, and the files in a folder.
- find files containing a textSearch every file under a folder for a word or a phrase, and show where it is.
- replace text in a fileChange every place a word or a phrase appears in a file, keeping a copy if you like.