I have 5 log files under different directores . say for eg abc under /home/dir1 , xyz under home/dir2 . is there a script that i can run from say /home that searchers all these files for string or combination of strings and write to a file
Here is my script :
#!/bin/ksh
#
# Start of main processing
#
echo "enter String One";
read SearchString1
echo "Enter String two";
read SearchString2
echo $SearchString1
for i in `cat Loginput`;
do
if [ "$SearchString2" == '' ];then
cat $i|grep $SearchString1 >>"Logoutput"
else
cat $i|grep $SearchString1|grep $SearchString2 >>"Logoutput"
fi
done
exit 0
I'm getting the below error :
Searchstring2 = Sep 29 00:00:10
error :grep: 0652-033 Cannot open 29.
grep: 0652-033 Cannot open 00:00:10
You need to quote "$SearchString1" to prevent word splitting when the variable is expanded. Think of it this way: if you typed in "grep Sep 29" it would think you were trying to look for the string "Sep" in the file "29." So when the shell expands $SearchString1, it is as if you had typed in "grep Sep 29" without any quotes. By quoting, you prevent the shell from splitting the argument into two words.
EDIT: There are a number of other problems, or at least inefficiencies in your script, but as a novice scripter myself, I understand that sometimes you just struggle through it to get the job done. Some things to consider:
1) Consider whitespace when writing scripts. Your script with meaningful whitespace:
#!/bin/ksh
# Start of main processing
echo "enter String One";
read SearchString1
echo "Enter String two";
read SearchString2
echo "$SearchString1"
for i in `cat ~/Desktop/Loginput`;
do
if [ "$SearchString2" == '' ]
then
cat $i|grep "$SearchString1" >>"Logoutput"
else
cat $i|grep "$SearchString1"|grep $SearchString2 >>"Logoutput"
fi
done
exit 0
I did move the "then" statement to its own line. While the whitespace means nothing to the shell, it makes it much easier for humans to read because you can see the organizational structure of your script.
2) ";" is not needed at the end of a line. The shell interprets a newline as the end of a command, unless it is quoted, in which case it is taken literally (example below):
echo "
"
3) It looks like you are testing whether the second search string is blank. An easier way to do this is simply [[ "$SearchString2" ]]. If the string is null, the test will return false, and the if command will execute the "else" portion of the construct.