I would like to find all php files on my server which first line or second line has more than N characters.

I would like to print both the file name and the line content that was found.

How would I do this? I am thinking on doing grep, but I don't know how to analyze lines on a file with it.


here's a way to do it:


for f in $(find / -iname  '*\.php'); do
  if [ $(head -n 2 "$f" | tail -n 1 | wc -c) -gt $MIN_WIDTH ] || [ $(head -n 1 "$f" | wc -c) -gt $MIN_WIDTH ]; then    
    echo "$f";

here's a breakdown:

  • look up all .php files: find / -regex '.*\.php$'
  • get the second line of the file and count the number of characters: head -2 "$f" | tail -1 | wc -c
  • get the first line of the file and count the number of chararcters: head -1 "$f" | wc -c
  • compare whether each is greater than $MIN_WIDTH: `[ $(…) -gt $MIN_WIDTH ]
  • if either of those is greater than $MIN_WIDTH: if […] | […]
  • printout the name of the file: echo "$f"
| improve this answer | |
  • It should be $MIN_WIDTH and you shoud add a head -n 2 "$f" after your echo "$f". And quote all $f variables. – erik Mar 6 '14 at 20:54

A somewhat shorter variant than zmo’s

find -iname "*.php" -exec grep -HP '.{6,}' {} \; | grep -P '^.+:[12]:'

where 6 is the minimum number of characters. The -H option is to print the filename even if only on file is grepped (this is the case, because every found file is grepped separately via the {} operator)

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.