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

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

file content:

lorem ipsum
trololo /foobar abc
dolor sit
/foobar def

shall afterwards be:

trololo /foobar abc
/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
  • Line number 1 to 4 is in your file or it is your simulation?
    – cuonglm
    May 15, 2014 at 14:13
  • 1
    grep has a recursive option -R
    – user60101
    May 15, 2014 at 14:34
  • -1 Why is 2. foobar def in the result when it doesn't include the specified string /foobar? Feb 21 at 23:34
  • @RobinA.Meade youre downvoting my question because of that? Cheers mate!
    – Alex
    Feb 25 at 14:44
  • @Alex I changed to an upvote after most recent edits. Feb 27 at 6:06

1 Answer 1


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' {} \;
  • find . -type f -exec find ./* -exec sed -i '/\B\/foobar\b/!d' {} \; errors: find: -exec: no terminating ";" or "+"
    – Alex
    May 15, 2014 at 15:21
  • find ./* -exec sed -i '/\B\/foobar\b/!d' {} \;errors sed: 1: "./myfile": invalid command code .
    – Alex
    May 15, 2014 at 15:21
  • still use this pretty often by the way, so powerful and fast. thanks again
    – Alex
    Jun 4, 2014 at 13:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.