1

How to limit the number of search results per folder, for example:

With this command:

grep --include=*.php -Ril '<?' '/var/www/'

I get the following:

/var/www/test.php
/var/www/test1.php
/var/www/phpinfo1.php
/var/www/phpinfoo.php
/var/www/phpinfooo.php
/var/www/1/php.php
/var/www/1/php3.php
/var/www/1/index.php
/var/www/1/indexed.php
/var/www/1/indexin.php
/var/www/test/tester.php
/var/www/test/info.php
/var/www/test/inform.php
/var/www/test/conf.php

And I need only 3 results per folder, and therefore it is:

/var/www/test.php
/var/www/test1.php
/var/www/phpinfo1.php
/var/www/1/php.php
/var/www/1/php3.php
/var/www/1/index.php
/var/www/test/tester.php
/var/www/test/info.php
/var/www/test/inform.php
1
  • What about grep's -m option ? or -c? Dec 1, 2014 at 7:42

2 Answers 2

2

The recursive grep will scan the entire tree and not care about directory structure. You need to traverse the structure and grep each directory individually.

find /var/www -type d -print | while read dirname; do grep -sil '<?' "$dirname"/*.php | head -3; done

The grep -s will handle conditions where there are no php files in a directory.

0

What about something like this?

for DIR in $( find ./test -mindepth 1 -type d ); do
    find "$DIR" -type f | grep "\.php" | head -n3
done

find ./test -mindepth 1 -type d lists all the directories in the test directory excluding the parent.

find "$DIR" lists the full path in each directory and then greps for the php extension and lists three with head.

mkdir test
cd test
mkdir dir{test,1,anotherdir} && touch dir{test,1,anotherdir}/file{a,b,c,d,e,f}.php
cd ..

Output:

./test/dirtest/filed.php
./test/dirtest/filec.php
./test/dirtest/filee.php
./test/dir1/filed.php
./test/dir1/filec.php
./test/dir1/filee.php
./test/diranotherdir/filed.php
./test/diranotherdir/filec.php
./test/diranotherdir/filee.php

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .