Can anyone explain this? The counter CDR_count should go on forever, but it suddenly resets at every step of the FOR loop (I know this because $_file has exactly 378 records). However, the counter reset is OUTSIDE the FOR loop. What's going on??
#!/bin/bash
if [ "$1" = "" ] || [ "$2" = "" ]; then
echo
echo "USAGE: ./CCN_CDR_parser.sh <CCN CDR files - path & wildcard allowed> <MSISDN>"
echo
exit
fi
echo
echo "Searching CDRs for MSISDN $2 in:"
echo "$1"
echo
file_count=0
file_total=`ls -1 $1 | wc -l | tr -d " "`
CDR_count=0
CDR_match=0
echo > CDR.tmp
for _file in `ls -1 $1`
do
echo -ne "Files processed: $file_count / $file_total CDRs match : $CDR_match / $CDR_count"\\r
file_count=`expr $file_count + 1`
cat $_file | while read _line
do
if [ "$_line" = "CDRCCN.ChargingDataOutputRecord.onlineCreditControlRecord" ]; then
CDR_count=`expr $CDR_count + 1`
echo "Files processed: $file_count / $file_total CDRs match : $CDR_match / $CDR_count"
if [ "`grep "servedAccount : '$2'" CDR.tmp`" != "" ]; then
CDR_match=`expr $CDR_match + 1`
mv CDR.tmp CDR$CDR_match.txt
echo -ne "Files processed: $file_count / $file_total CDRs match : $CDR_match / $CDR_count"\\r
fi
CDR_start="true"
else
CDR_start="false"
fi
if [ "$CDR_start" = "true" ]; then
echo $_line > CDR.tmp
else
echo $_line >> CDR.tmp
fi
done
done
echo
echo
Using a pipe puts the loop into a subshell. Any variable changes inside it aren't reflected outside the loop, and once the loop finishes, the subshell ceases to exist. It's kind of like the difference between running a script and sourcing it.
Always a pleasure to read your posts! Nice way of removing spaces by using arithmetic expansion.
Other benefits of this method are that it also correctly counts file names that contain newlines (whereas ls|wc -l does not) and that there are no command line length limitations..