Shell – How to find text in files and only keep the respective matching lines using the terminal on OS X

findgrepshell

I am pretty new to the terminal and command lines, from what I have found out grep seems to be the right tool for search files for specific text strings.

I have a folder with many huge text files and I would like to to only keep those lines of each file that contains a certain string (e.g. "/foobar"., for instance:

file1 (no file ending)

 1. lorem ipsum
 2. trololo /foobar abc
 3. dolor sit
 4. foobar def

shall afterwards be:

 1. trololo /foobar abc
 2. foobar def

I guess the command looks something like this

grep -wE "(/foobar)" 

but I have no clue how to tell the command to only keep those lines and do that for each file that you find in the current folder.

Would you do that with find or does grep have an own functionality for that? Something like:

find ./* -exec do grep stuff here

Best Answer

grep would only find lines matching a pattern in a file, it wouldn't change the file. You could use sed to find the pattern and make changes to the file:

sed '/\B\/foobar\b/!d' filename

would display lines matching /foobar in the file. In order to save changes to the file in-place, use the -i option.

sed -i '/\B\/foobar\b/!d' filename

You could use it with find too:

find . -type f -exec sed -i'' '/\B\/foobar\b/!d' {} \;