I am trying to search several logs for a text string, make it validate with a condition and print the name of the file and a text:
ls -ltrh | awk '{
if ($0 ~ /successfully completed/) {print FILENAME,FECHACREACIÓN,"COMPLETADO_CORRECTAMENTE"}
else {print FILENAME,FECHACREACIÓN,"ERROR"}
};' *.log
The idea is that it validates in the last line if there is a string "successfully completed" and if it exists, it shows me COMPLETED CORRECTLY, and if it doesn't, it shows me an error.
But currently the chain does exist and it throws me an error.
For starters,
ls -ltrh
it doesn't give you a reasonable format to process with laterawk
, and the other problem is that you'd be printing a message for each line read.One way would be combining
bash
andawk
:On the script side
awk
Much more compact is @fedorqui's suggestion to use the rule
ENDIFLE
, available in GNU Awk, with which we avoid having to preprocessbash
files:We use the rule
END
to execute just when we have read the entire file, we check if just the last line has the searched text. What is not optimal is that itawk
reads the entire file even though we only need the last row. Maybe a solution usingtail
is better.In the case of
ENDFIILE
, it enters this block every time it finishes processing a file.I like Patricio Moracho's answer.
To complement it, I suggest you use a series of processes:
Basically, this loops through all the files
*.log
automatically (instead of parsing the output ofls
, which can be dangerous ) and extracts the last line. It does agrep
silent to her that if it finds the text "successfully completed" it returns success and launches theecho "completado correctamente"
"error" and if not.