Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi,
I need to extract messages from a log file between two known character strings "eyecatchers". what could be the logic to do this using only k shell script commands?
TIA
aj

So it would be something to the effect of
eyecatchers
messages
messages
messages
messages
messages
eyecatchers
?Are the eyecatchers actually the word eycatchers? Are they on their own separate line?

Well assuming the file looks like above, here is a quick n dirty solution.
#!/bin/ksh
counter=1
xconter=2
while [[ `grep -A$counter eyecatchers testinput | head -$xconter | tail -1 | grep eyecatchers` = "" ]];do
grep -A$counter eyecatchers testinput | head -$xconter | tail -1 >> outputfile
counter=$(($counter+1))
xconter=$(($xconter+1))
done
echo Done!

awk comes with ksh, so that means it qualifies. The following solution prints the triggering lines as well as the lines between. To not print the triggering lines, just take out the "print" command that follows k++.
awk '{\
if (match($0,"eyecatchers"))
{k++
if (k==1) next
if (k==2) exit }
if (k==1) print
}' logfile

awk does not come with ksh. It is a unix (and now DOS/Windows/etc...) utility and is its own interpreter. awk is a great tool and does a good job at what this person wants. However, many companies (and don't ask me why)don't want awk in their shell scripts. It may be due to the quality of some alleged "system administrators" who cannot write simple shell scripts without a great deal of trouble. awk could well be beyond anything they could master. Saying that awk comes with the Korn shell is not correct. For that matter, neither does grep/tail/head used in the other example. It would not be difficult to use pattern matching available in the Korn shell to do this task. If I was reading a very large file I would do it all in the shell or write an awk script. All the extra calls to head/tail/grep are not necessary.
When someone asks how to write a script using just Korn shell commands, I assume they want to use the built-ins. This task can be done with built-ins. This simple script will find the first instance of the "eyecatcher". It could be easily written to parse the entire file and find each instance.
#!/bin/ksh
start=0
while read line
do
case $line ineyecat* ) if [ $start = 0 ]
then
start=1
else
echo $line
exit
fi
;;
esac
if [ $start = 1 ]
then
print $line
fi
done < junk2.datI am not saying this is the best way to do it but it does use only Korn shell built-ins.
Jerry

![]() |
printf help
|
IF condition after substr
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |