Looping through directory for file and do a word count

Hello All.

I am working on a script which basically loop through a directory for files and does a word count for each file and if the file has more than 1 row then writes that filename to a log file.

1. Loop thorugh a directory and pick up files
2. do a word count on each file
3. write the filename to a logfile only if the file has more than 1 record.

I have a written some code and it works but it is writing all files to logfile
for file in `ls`
do
 Count=`echo cat $file |  wc -l`
echo " my count is $Count"
if [ "$count" -gt 1 ];
then
echo $count
echo $file >> /home/log.txt
else
 echo "there is no file to write"
fi
done

Open in new window

antvuAsked:
Who is Participating?
 
mostartConnect With a Mentor Commented:
also remove the "echo" in line 3.
0
 
mostartCommented:
watch your case. $Count is initialized with capital C and later you are using lower case c..
0
 
antvuAuthor Commented:
I  changed the case with upper case C and executed the script.. below is the result i got
my count is 1
there is no file to write
 my count is 1
there is no file to write
 my count is 1
there is no file to write
 my count is 1
there is no file to write
___________________________

I have 4 files in the directory , one of the files has 1 record and other 3 have more than 1 ..
0
 
antvuAuthor Commented:
Thanks mostart.. that worked.
I am closing the question now.
0
 
TintinCommented:
Let's remove redundant code and shorten
#!/bin/bash
for file in *
do
  [ -f $file ] || continue  # Skip non-files
  lines=$(wc -l <$file)
  [ $lines -gt 1 ] && echo $file >>/home/log.txt
done

Open in new window

0
All Courses

From novice to tech pro — start learning today.