Find the answer to your Linux question:
Results 1 to 3 of 3
Hello I use 'grep -Ri "mypattern" .' to search for all files in the current directory recursively that contain "mypattern". But this command returns every single occurence, so that if ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Linux Newbie
    Join Date
    Nov 2007
    Posts
    127

    Question [SOLVED] Restrict output to display one file each?


    Hello

    I use 'grep -Ri "mypattern" .' to search for all files in the current directory recursively that contain "mypattern".

    But this command returns every single occurence, so that if a given file has several occurences of the pattern, the screen fills up pretty quick.

    More than likely, there's a way to restrict the output so that it only displays each file once, no matter how many occurences it contains, but I couldn't find how to do it.

    Does someone know?

    Thank you.
    Last edited by MikeTbob; 07-27-2010 at 01:22 PM.

  2. #2
    Just Joined!
    Join Date
    Mar 2010
    Posts
    79
    grep -c will:
    Code:
      -c, --count
                  Suppress  normal output; instead print a count of matching lines
                  for each input file.  With the -v,  --invert-match  option  (see
                  below), count non-matching lines.  (-c is specified by POSIX.)
    But it will also list the files which contain 0 occurences of <pattern>.


    I did a bit of playing and came up with this
    (search for the pattern "test" in all files in the current directory) :
    Code:
    #!/usr/bin/env bash
    
    for e in *
    do
        grep test $e > /dev/null
        if [ "$?" -eq 0 ]
        then
            echo "at minimum one occurence of test in $e "
    #    else
    #        echo "no occurence of test in $e "
        fi
    done
    There must be a better way, but none i can think of.

  3. #3
    Linux Newbie
    Join Date
    Nov 2007
    Posts
    127
    Found it: I should have thought about checking the possible switches before asking :-/ Simply add the "l" switch:

    'grep -Ril "mypattern" .'

    Thank you.

  4. $spacer_open
    $spacer_close

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •