uss
uss

Reputation: 1309

How do I list the files having particular strings from group of directories in bash?

I want to list files having EXACT strings like "hello", "how" and "todo" from a directory (which is having multiple directories). Also I want to list c(.c) and cpp (.cpp) files only. I have tried with grep -R (grep -R "hello" /home) but not satisfied. Please help me to enhance my grep -R command or any alternate way. Thanks in advance.

Upvotes: 1

Views: 292

Answers (3)

rakib_
rakib_

Reputation: 142545

You can try the followings:

      grep -rn --include={*.c,*.cpp} yourdirectory -e ^h[a-z]*

This will search through all the files which have .c and .cpp extensions and finds patterns starts with h (you need to prepare you own to meet your need) from your specified directory.

Upvotes: 0

umläute
umläute

Reputation: 31264

if you want to find files, a good start is usually to use find.

if you want to find all .cpp and .-c files that contain the strings "hello", "how" or "todo" in their content, use something like:

find /home \( -name "*.c" -or -name "*.cpp" \) \
    -exec egrep -l "(hello|how|todo)" \{\} \;

if instead you want to find all .cpp and .-c files that contain the strings "hello", "how" or "todo" in their filenames, use something like:

find /home                                                       \
   \( \( -name "*.c" -or -name "*.cpp" \)                        \
      -and                                                       \
      \( -name "*hello*" -or -name "*how*" -or -name "*todo*" \) \
   \)

there is a bit of quoting (using \) involved, as (), {} and ; are considered special characters by the shell...

Upvotes: 2

Naruil
Naruil

Reputation: 2310

In fact grep itself would be fine for this.

However I would strongly suggest ack-grep. It is a good alternative to grep which just suit your need.

You can find it here

With ack-grep it is just as simple as

ack-grep --cc --cpp "(hello|how|todo)"

Upvotes: 0

Related Questions