I have a file like this. Pls help me to solve this in ksh
(I should look for only Message : 111 and need to print the start time to end time
Need to ignore other type of messages. Ex: if first message is 111 and second message is 000 or anything else then ignore the 2nd one and print start time of the first message. )
#!/usr/bin/env ksh
while read line
do
if [[ $line == *" : 111" ]] # line with your flag
then
if [[ -z $start_time ]] # dont have start; save start
then
start_time="${line%%,*}" # ditch all from first comma to end of line
else # have start, just update end
end_time="${line%%,*}"
fi
else # not our line, print out last start/end pair
if [[ -n $end_time ]] # but only if we have a pair and not printed
then
printf "%s to %s\n" "$start_time" "$end_time" # print times
start_time="" # next time we see is a start time
end_time=""
fi
fi
done <input-file
if [[ -n $end_time ]] # handle last case, but only if both seen
then
printf "%s to %s\n" "$start_time" "$end_time" # print times
fi
Yes, the code sample I gave assumed that there was always a start/end pair. You didn't mention how to handle the case that you've pointed out.
Small change below handles this case now.
#!/usr/bin/env ksh
while read line
do
if [[ $line == *" : 111" ]] # line with your flag
then
if [[ -z $start_time ]] # dont have start; save start
then
start_time="${line%%,*}" # ditch all from first comma to end of line
else # have start, just update end
end_time="${line%%,*}"
fi
else # not our line, print out last start/end pair
if [[ -n $end_time ]] # print pair if we have both
then
printf "%s to %s\n" "$start_time" "$end_time" # print times
else
if [[ -n $start_time ]]
then
printf "%s\n" "$start_time"
fi
fi
start_time="" # next time we see is a start time
end_time=""
fi
done <input-file
if [[ -n $end_time ]] # handle last case, but only if both seen
then
printf "%s to %s\n" "$start_time" "$end_time" # print times
else
if [[ -n $start_time ]]
then
printf "%s\n" "$start_time"
end
fi