2

I am trying to display all files which contain a specific word on more then three lines.

i.e. file:

Andrew is so nice, 
and Andrew want some ice,
but Andrew doesn't roll the dice.

So this file contains Andrew on more than three lines, so it will be displayed.

I used grep -or '\' but it list all files which contain "word" on at least 1 line.

4

Try

  grep -c Andrew * | awk -F: '{if ($2 >=3) print $1}'

It works because grep -c prints "file:count" for each file, and -F: tells awk that the colon separates fields.

2

The following shell script may be useful:

#!/bin/bash

if [ $# -ne 2 ];then
  echo "Usage: `basename $0` DIRECTORY STRING"
  exit 1
fi

for file in $1/* ; do
    if [ `cat $file 2>/dev/null | grep -c $2` -ge 3 ]; then 
        echo $file
    fi
done

The script should be run with two arguments:

  • DIRECTORY - the directory where you want to search for files which contains a word on more then three lines

  • STRING - the word for seeking.


Or, in a single command for files from the current directory and the word "Andrew":

for file in *;do if [ `cat $file 2>/dev/null|grep -c Andrew` -ge 3 ];then echo $file;fi;done
  • 3
    Or more concisely: for f in ./*; do [[ $(grep -c Andrew "$f") -ge 3 ]] && echo "$f"; done – evilsoup Aug 22 '13 at 16:01

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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