I am looking out for a command to use both GREP and FIND to achieve the below-listed condition.

Every log file contains the string pattern "226 transfer complete" which occurs twice. In some files, it occurs only once or nil. I need to capture the list of file names with zero and one occurrence. Following command works ONLY if the search pattern not found in the file (i.e for count 'ZERO' only).

find . -type f -name "*.log" ! -exec grep -q "226 Transfer complete." {} \; - print

I am using the grep version (GNU grep) 2.20. I need to capture the results in the text file as well.

  • 1
    So what results do you want, exactly? You want to ignore whether the string occurs in the top portion of the file and only report the filename if the string is in the bottom portion of the file? (That was my guess but @don_crissti interpreted it entirely differently. This evinces that your question is too ambiguous to be answered in its current form; please edit the question to clarify.)
    – Wildcard
    Commented Jan 24, 2017 at 19:26
  • sorry for the confusion. I want to ignore the file with the PATTERN "226 transfer complete." located in the file twice. i.e top and the bottom portion of the file. As a result, it should list the file names meeting both the following conditions - with PATTERN present nowhere in the file as well PATTERN present either in top or bottom portion of the file. .
    – bala yuva
    Commented Jan 24, 2017 at 19:43
  • Can your pattern appear more than twice in a file? Can your pattern appear anywhere other than first and/or last line? In other words can we reduce the problem to counting occurrences of the pattern? Commented Jan 24, 2017 at 21:13
  • @don_crissti. Your command is exactly what I am looking for. It works. Apologies if my question was as clear as mud. Appreciate your patience and help.
    – bala yuva
    Commented Jan 24, 2017 at 21:33
  • I totally agree with you. I will correct it as I am very new to this forum. Thanks for your time and help. I am not sure how to give UP VOTE to your answer as it was in comment discussion.
    – bala yuva
    Commented Jan 24, 2017 at 21:48

2 Answers 2

grep -lR '226 Transfer complete\.' --include='*.log'

You could use awk to count occurrences and print the file name if the count is less than n:

find . -type f -name \*.log -exec awk -vn=2 'BEGIN{c=0};
/PATTERN/{++c; if (c==n){exit}};END{if (c<n){print FILENAME}}' {} \;

This will stop counting as soon as n (in this case 2) matches are found.

  • i am trying to capture the results in a text file. I tried the below one. It dint work. Can you advice what mistake i had done. find . -type f -name *.log -exec awk -vc=0 '/226 Successfully transferred/{c++}END{if (c<1){print FILENAME}}' {} + > /homedir/test_log.txt
    – bala yuva
    Commented Jan 24, 2017 at 22:25

You must log in to answer this question.

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