Pages

Tuesday, October 23, 2012

How to grep in shell script...

The task is there is a file containing one column of entries. Write a script to compare the o/p of one command and check whether the output matches with any row of that file (supported.txt file).

$cat supported.txt
SAS2308_2(C1)
SAS2308_2(D1)

Assume $devInfo gives us a string that contains like the rows of support.txt file. If there is a match between the o/p of $devInfo in that file, then do nothing, else warn.

checkSupportedFwDev() {
        local supportedControllerList=`cat supported.txt`
        #Get the controller name from $devInfo and compare that with $supportedControllerList
        local currentController=`echo "${devInfo}" | grep "Controller" |grep -v Number | awk '{ print $NF }'`
        #echo "currentController=[$currentController]"
        local supported=`echo "${supportedControllerList}" | grep $currentController`
        if [ -z ${supported} ]
        then
                echo "Warning: This adapter [${currentController}] is not officially supported."
        fi
        }

Another approach to do the same:

checkSupportedFwDev() { 
        #Get the controller name from $devInfo and compare that with $supportedControllerList
        local currentController=`echo "${devInfo}" | grep "Controller" |grep -v Number | awk '{ print $NF }'`

        if ! grep "^${currentController}\$" supported.txt >/dev/null 2>&1;
        then
                echo "Warning: This adapter [${currentController}] is not officially supported."
        fi

}

Which approach you like and why?





No comments: