0

Using grep to print a keyword in a log to the output file

grep -i -n "application" /app/log1.log > L1.log

Now this gives results if it finds application in the log. But also results empty l1 log file where there are no results.

Would like assistance in creating the l1.log only when there are results.

1 Answer 1

1

Now this gives results if it finds application in the log. But also results empty l1 log file where there are no results.

Correct.
Using the ">" redirection operator pre-deletes the target file.

Would like assistance in creating the l1.log only when there are results.

Use a temporary file to capture any number of results and use grep's exit status to determine whether or not it found anything.

TMP_LOG=/tmp/log.$$

grep -i -n "application" /app/log1.log > ${TMP_LOG}

if [ 0 -eq $? ] ; then
  # At least one Match found 
  cat ${TMP_LOG} > L1.log
  rm ${TMP_LOG} 
fi

You must log in to answer this question.

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