Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 0 down vote accepted

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"
share|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)

share|improve this answer

You must log in to answer this question.

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