Find a string in all files and echo a message

Hi. I m trying to figure out how to do this.

I have a directory full of files (100 files) and I want to be able to search for a string called "end" at the end of the files (last line or last 5 lines) and echo each file to say "incomplete" if not found.

This is what I have so far.

---

for file in 'ls';do
    Incomplete='tail -5 $file | grep end';
    if [[ $file -ne "$Incomplete" ]];then
        echo "$file is incomplete.";
    fi
done

----

When i run the script, it says:

-bash: [[: tail -5 $file | grep end: syntax error: invalid arithmetic operator (error token is "$file | grep end")

I have no clue yet. Can someone help to explain? Thanks a ton.

[[  $file -ne "$Incomplete" ]]

-ne is meant for number comparisons
!= is meant for string comparisons

So,

[[  $file != "$Incomplete" ]]

Note - your corrected code does not make sense to me. Why would the $file value ever equal the $Incomplete value? The file name is not "end"

Investigate the use of the grep -q command It sets the return value to 0 (OK) if "end" is found in the last five lines, snippet:

tail -5 $file | grep -q "end"
if [ $? -eq 0 ] ; then
  echo "$file is okay"
else
  echo "$file is not ok"
fi
1 Like

Thanks Jim. I m still learning. I need to read up some more.

The syntax error in the script is due to using apostrophes ' in lieu of backticks ` , so that Incomplete has the string contents tail -5 ... . Please note that backticks are deprecated, use the $(...) construct instead for "command substitution".
The comments on the semantics by jim mcnamara still apply.

You could use this in bash as well:

for f in * ; do
	if tail -5 "$f" | grep -q -i end$
	then	echo "File $f: valid"
	else	echo "File $f: incomplete"
	fi
done

hth