Script to recursively grep data from certain files in the directory

Posted by Jude on Ask Ubuntu See other posts from Ask Ubuntu or by Jude
Published on 2012-09-28T02:47:18Z Indexed on 2012/09/28 3:49 UTC
Read the original article Hit count: 308

Filed under:
|

I am making a simple shell script which will minimize the time I spend in searching all directories under a parent directory and grep some things inside some files. Here's my script.

#!/bin/sh
MainDir=/var/opt/database/1227-1239/

cd "$MainDir"

for dir in $(ls); do

grep -i "STAGE,te_start_seq Starting" "$dir"/his_file | tail -1 >> /home/xtee/sst-logs.out

if [ -f "$dir"/sysconfig.out];
then
    grep -A 1 "Drive Model" "$dir"/sysconfig.out | tail -1 >> /home/xtee/sst-logs.out
else
    grep -m 1 "Physical memory size" "$dir"/node0/setupsys.out | tail -1 >> /home/xtee/sst-logs.out
fi

done

The script is supposed to grep the string STAGE,te_start_seq Starting under the file his_file then dump it sst-logs.out which it does. My problem though is the part in the if statement. The script should check the current directory for sysconfig.out, grep drive model and dump it to sst-logs.out if it exists, otherwise, change directory to node0 then grep physical memory size from setupsys.out and dump it to sst-logs.out. My problem is, it seems the if then else statement seems not to work as it doesn`t dump any data at all but if i execute grep manually, i do have data.

What is wrong with my shell script? Is there any more efficient way in doing this?

© Ask Ubuntu or respective owner

Related posts about command-line

Related posts about scripts