I need to accomplish following shell script. I trying to extract the HOSTNAME after it runs Successful via Ansible Playbook Run.
I have text file which contains Ansible-Playbook run command to be executed and writing the output into the log file: result.log
Here is what's the "result.log" file looks like
PLAY RECAP *********************************************************************
TESTLINUX01 : ok=6 changed=1 unreachable=0 failed=0If the failed is "0", Unreachable is "0" and Changed is more then 0, then print the HOSTNAME only. In this case, TESTLINUX01
Thank you for your help.
32 Answers
You can use someting like this:
#!/bin/bash
file="result.log"
changed=`grep -Po "changed=\K\d+" $file`
unreachable=`grep -Po "unreachable=\K\d+" $file`
failed=`grep -Po "failed=\K\d+" $file`
if [ $changed -ge 1 -a $unreachable -eq 0 -a $failed -eq 0 ] then cut -s -f1 -d: $file | tr -s ' '
fiFirst we extract all necessary values then we compare them with your desired ones, if they where match we print out the host name.
grep -Po "changed=\K\d+returns the number in front of "changed"- IF statement:
$changed -ge 1if changed is greater that equal "1"-aand$unreachable -eq 0unreachable was equal to "0"-aand$failed -eq 0failed was equal to "0", Then:
cut -s -f1 -d: $file | tr -s ' 'prints the hostname
Thank you all for replying and providing the solution. Following code works out for me:
cat $file
$file >> $LOGFILE
SUCCESS=`grep "unreachable=0 failed=0" $LOGFILE | awk '{printf "%s ", $1;}'`
echo "Success: $SUCCESS"
FAILURE=`grep -E "unreachable=0 failed=[1-9]" $LOGFILE | awk '{printf "%s ", $1;}'`
echo "Failure: $FAILURE"
Unreachable=`grep -E "unreachable=1 failed=0" $LOGFILE | awk '{printf "%s ", $1;}'`
echo "Unreachable: $Unreachable"