Use GREP to count number of records and place it in a variable

I am trying to count the number of records from different files using grep , and then place the result in a separate variable for each file, so at the end of my shell script, I can sum all the variables and check if the number of records are equal to what I was expecting. It is weird but wc -l does not give me the correct number of records for the files. So for this scenario I have to use only grep command. Please see below how I was trying to use the command:

Total_records_file1=`grep -c '.*' file1.txt`
Total_records_file2=`grep -c '.*' file2.txt`
.
.
.
Total_records_file(n)=`grep -c '.*' file(n).txt`

Where (n)=Nth number of file

I have also tried escaping the single quotes like below and it doesn't work

Total_records_file1=`grep -c \'.*\' file1.txt`
Total_records_file2=`grep -c \'.*\' file2.txt`
.
.
.
Total_records_file(n)=`grep -c \'.*\' file(n).txt`

and then sum up the variables using the code below:

Total_Sum_of_Records_in_Files=`expr ${Total_records_file1:-0} + ${Total_records_file2:-0} + ...... + ${Total_records_file(n):-0}`

Please advise if there are any other suggestions...

try

var=$(awk 'END{print NR}' file1 file2 file3)
1 Like

Not sure why wc -l should NOT give you the correct No. of lines unless some of your files are not text files (e.g. <newline> missing at the end of file). Wouldn't cat file*.txt|wc -l give you the right line count?