Results 1 to 7 of 7
I am trying to count the # of a files with a certain pattern in a directory. This is what I have written. The shell is bash.
function counter(){
z=0;
...
- 09-11-2008 #1Just Joined!
- Join Date
- Sep 2008
- Location
- Washington DC
- Posts
- 5
A "counter" in Linux
I am trying to count the # of a files with a certain pattern in a directory. This is what I have written. The shell is bash.
function counter(){
z=0;
for i in $( ls | grep "$pattern*" ); do
z = `expr $z + 1`
done
if test `expr $z` -lt 10
then echo v0$z
else
echo v$z
fi
}
My error is "bash: z: command not found" I have been messing with all sorts of specifications of the for loop, and I can't seem to make it work. Help anyone?
The last if statement is just more of a formatting thing than anything else.
(I only started even touching linux like a month ago, so I know there is probably a much better way to do this)
- 09-11-2008 #2Instead of saying this:My error is "bash: z: command not found"
say this:Code:z = `expr $z + 1`
Hope this helps.Code:z=`expr $z + 1`
--
Bill
Old age and treachery will overcome youth and skill.
- 09-12-2008 #3Just Joined!
- Join Date
- Sep 2008
- Location
- Washington DC
- Posts
- 5
It worked. Thank you!
- 09-12-2008 #4Linux User
- Join Date
- May 2008
- Location
- NYC, moved from KS & MO
- Posts
- 251
Using ls to count files is not reliable. For example, create these two files under a folder:
touch hello "hello world"
then run your code
z=0
PATTERN="hello*"
for i in $( ls | grep "$PATTERN" ); do z=`expr $z + 1`; done
echo $z
you get 3 instead of 2 as a result
I would use command find combined with wc instead, like this:
PATTERN="hello*"
find . -name "$PATTERN" | wc -l
- 09-12-2008 #5Just Joined!
- Join Date
- Sep 2008
- Location
- Washington DC
- Posts
- 5
Thank you for your suggestion. I am not sure it is necessary, but I implemented it, my pattern is very distinctive, and it is good programming practice.
Also good to know for future reference. Thank you.
- 09-12-2008 #6Linux Guru
- Join Date
- Nov 2007
- Location
- Córdoba (Spain)
- Posts
- 1,513
In fact, and since he explictly said he uses bash, there's not even need for find (as long as he don't need to recurse subdirs), just use
But yeah, if you prefer to use find, it's smarted to use wc -l as you said, instead of a loop.Code:z=0; for i in ${PATTERN}; do z=$((z+1)); done;
OSS goodnes, zillions of ways to accomplish a given goal.
- 09-13-2008 #7Linux User
- Join Date
- May 2008
- Location
- NYC, moved from KS & MO
- Posts
- 251
You can use option -maxdepth 1 in command find to disable the recursive feature.
PATTERN="hello*"
find . -maxdepth 1 -name "$PATTERN" | wc -l


Reply With Quote
