LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   h (https://www.linuxquestions.org/questions/linux-newbie-8/h-230716/)

jwprz70 09-14-2004 09:16 PM

help!
 
How do I write Shell Script that counts the number of files in a directory then prints the number.

foo_bar_foo 09-14-2004 10:21 PM

don't kow how to do a shell script but use this
c is lots faster
name it count_files.c
or whatever you want
compile with
gcc -o count_files count_files.c

then put the executable in usr/bin or wherever
you can also call this from a script of course
count_files will get you the regular files in current working directory
or you can put a path to a directory as an argument after the command

if you want more than regular files counted change it or write back
Code:

#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int get_file_type (const char* path)
{
  struct stat st;
  lstat (path, &st);
  if (S_ISREG (st.st_mode))
    return 0;
  else return 1;
 }

int main (int argc, char* argv[])
{
  char* dir_path;
  DIR* dir;
  struct dirent* entry;
  char entry_path[PATH_MAX + 1];
  size_t path_len;
  int type;
  int count = 0;
  if (argc >= 2)
    dir_path = argv[1];
  else
    dir_path = ".";
  strncpy (entry_path, dir_path, sizeof (entry_path));
  path_len = strlen (dir_path);
  if (entry_path[path_len - 1] != '/') {
    entry_path[path_len] = '/';
    entry_path[path_len + 1] = '\0';
    ++path_len;
  }
  dir = opendir (dir_path);
  while ((entry = readdir (dir)) != NULL) {
    strncpy (entry_path + path_len, entry->d_name,
            sizeof (entry_path) - path_len);
    type = get_file_type (entry_path);
    if (type == 0) count++;
  }
  printf ("%i\n", count);
  closedir (dir);
  return 0;
}


win32sux 09-14-2004 10:57 PM

Re: help!
 
Quote:

Originally posted by jwprz70
How do I write Shell Script that counts the number of files in a directory then prints the number.
here's one way you could do it:

Code:

#!/bin/sh
COUNT=`ls -al | wc -l`
SNIP="3"
NUMBER=$(($COUNT-$SNIP))
echo $NUMBER

this would count all files in the current directory, including the hidden ones...

basically it lists all files in the current directory, then counts the lines that were listed...

the SNIP is there cuz when you do a "ls -al" there's two lines that represent "./" and "../" and one line that represents the total size, so we subtract them...

just my two cents...


Tinkster 09-14-2004 11:01 PM

Use -A instead of -a and 1 instead of l
and forget about snip ;)


Cheers,
Tink

win32sux 09-14-2004 11:07 PM

Quote:

Originally posted by Tinkster
Use -A instead of -a and 1 instead of l
and forget about snip ;)


Cheers,
Tink

yup, that's much better... thanks Tinkster!!!

=)

Code:

ls -A1 | wc -l

Tinkster 09-14-2004 11:43 PM

/me takes a bow:"Pleasure, mate!" ;)


All times are GMT -5. The time now is 12:40 AM.