3

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
  • Line number 1 to 4 is in your file or it is your simulation? – cuonglm May 15 '14 at 14:13
  • 1
    grep has a recursive option -R – BroSlow May 15 '14 at 14:34
3

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