Paul
Paul

Reputation: 1327

Finding text inside a folder using terminal

I am trying to find a line of code in a folder and using the terminal. I use this command, which I think should work:

MacBook-Pro:myWordpress myId$ grep "<?php get_template_part('loop', 'archives'); ?>" -R

where the folder I am inspecting is called "myWordpress". But I get this:

grep: warning: recursive search of stdin

I don't use much the terminal, so I am unsure as to how to do what I want. Any help appreciated. Thanks

David

Upvotes: 18

Views: 29401

Answers (4)

Gayal Kuruppu
Gayal Kuruppu

Reputation: 1391

For macOS this will be super useful and easy, and also it highlights the search result matches of text!

brew install ack 
ack "text"

enter image description here

Upvotes: 5

Ed Morton
Ed Morton

Reputation: 203684

Never use -r or -R with grep. It is a terrible idea, completely unnecessary (the UNIX tool to find files is named find!), and makes your code GNU-specific.

Best I can tell without any sample input/output, all you need is:

grep "<?php get_template_part('loop', 'archives'); ?>" *

or if you have files AND directories in your current directory but only want to search in the files:

find . -type f -maxdepth 1 -exec grep -H "<?php get_template_part('loop', 'archives'); ?>" {} +

or to search in all sub-directories:

find . -type f -exec grep -H "<?php get_template_part('loop', 'archives'); ?>" {} +

If that doesn't do what you want then provide the sample input/output in your question.

Upvotes: 1

juzraai
juzraai

Reputation: 5943

You have to specify the directory too as the last argument:

grep -r -F "string to search" /path/to/dir

Or if you want to search in current directory, write . as the target directory:

grep -r -F "string to search" .

If you don't specify a directory, grep will try to search in the standard input, but recursive search does not make sense there - that's why you get that warning.

The manpage for grep says that:

Not all grep implementations support -r and among those that do, the behaviour with symlinks may differ.

In this case, you can try a different approach, with find and xargs:

 find /path/to/dir -name '*.*' -print0 | xargs -0r grep -F "string to search"

Again, you can write . as the directory parameter (after find) if you want to search in the current directory.

Edit: as @EdMorton pointed out, the -F option is needed for grep if you want to search for a simple text instead of a regular expression. I added it to my examples above as it seems you are trying to search for PHP snippets that may contain special characters, which would lead to a different output in regexp mode.

Upvotes: 29

nbari
nbari

Reputation: 26925

I would suggest giving a try to ripgrep

$ brew install ripgrep

Besides been faster it gives you multiple options, check the examples

Once you have it installed just need to do:

$ rg your-string 

Upvotes: 3

Related Questions