LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   grep and path name matching. (https://www.linuxquestions.org/questions/linux-software-2/grep-and-path-name-matching-820290/)

stf92 07-16-2010 06:05 PM

grep and path name matching.
 
Linux kernel 2.6, Slackware 12.0.
Hi:

Question: I do grep -r string_1 .*txt. Is the path first expanded by the shell? If not, then say, ./elem1/elem2/file1.txt would search for string_1. However, it will not in my system. Note: '.' (period) in .*txt is any char. '.' in ./elem1/elem2/file1.txt is current dir. Now, .*txt should be, as a regexp, zero or more occurrences of any char followed by txt, that is, any string with txt as a suffix. Thanks.

ShadowCat8 07-16-2010 07:05 PM

Well,

If I were to try to find all files referencing string_1 in files that were ending in ".txt", I think I would try something like this:
Code:

~ $ grep -r string_1 --include=*.txt ./*
or, to make more sense of it and cut down possible false results:
Code:

find . -name "*.txt" -print | grep string_1
HTH. Let us know.

stf92 07-16-2010 08:26 PM

Thanks. The first command seems to work fine, although it would be difficult to test for "false results". As for the second one, I think you have missed something, for grep would then be looking into the path names and not into the contents of the files themselves. Regards.

ShadowCat8 07-26-2010 02:03 PM

Greetings,

@stf92: You are correct. My fingers got ahead of my brain while I was typing and missed the (ahem...) cat. Hehe ;)

So, really, the right way to do it for the second one would be something like:
Code:

for x in `find . -name "*.txt" -print`
    do
    cat ${x} | grep string_1
    if [ "$?" -eq "0" ]
          echo -e "File ${x} contains string_1.\n"
          fi
    done

HTH.


All times are GMT -5. The time now is 09:28 AM.