-4

I need to count all the files present in a directory and all its subdirectory with specific file extensions using shell script. Ex: I want a count of all the .py and .sh files in a directory and its subsequent subdirectories.

Sorry I missed to put in that I started with

find . -type f | sed -n 's/..*\.//p' | sort | uniq -c

but this is not printing anything

Nic3500
  • 8,144
  • 10
  • 29
  • 40
pavan kumar
  • 75
  • 1
  • 7
  • 1
    We encourage questioners to show what they have tried so far to solve the problem themselves. – Cyrus Apr 17 '23 at 19:50
  • See [How can I get a count of files in a directory using the command line?](https://unix.stackexchange.com/q/1125/264812). – pjh Apr 17 '23 at 20:34
  • @Cyrus sorry I missed to put that part ... – pavan kumar Apr 17 '23 at 21:09
  • Your current find command finds all files not just the .py and .sh files. You could start by amending your find to something like `find . -type f \( -name "*.py" -o -name "*.sh" \)` – j_b Apr 17 '23 at 21:35
  • 3
    Notice that unix files don't have extension – Diego Torres Milano Apr 17 '23 at 21:45
  • Also see [Is there a bash command which counts files?](https://stackoverflow.com/q/11307257/4154375), [Recursively counting files in a Linux directory](https://stackoverflow.com/q/9157138/4154375), [Script to find recursively the number of files with a certain extension](https://stackoverflow.com/q/69988369/4154375), and [BashFAQ/004 (How can I check whether a directory is empty or not? How do I check for any *.mpg files, or count how many there are?)](https://mywiki.wooledge.org/BashFAQ/004). – pjh Apr 17 '23 at 23:12
  • It's not clear from your question, whether you know in advance what "extension" you want to look at (i.e. `.py`), or whether your program needs to find out what "extensions" exist in your directory tree and then produces a count for **all** of them. – user1934428 Apr 18 '23 at 06:11
  • I want to consider all the extensions that are available in a directory and its subdirectory – pavan kumar Apr 19 '23 at 13:22

1 Answers1

0

To get all the extensions counted:

find . -type f -print | awk -F . '{print $NF}' | sort | uniq -c | sort -n

If you want to limit the type of files, you can add -name options to the find command.

find . -type f -name "*\.txt" -print | awk -F . '{print $NF}' | sort | uniq -c | sort -n

You can combine multiple -name options like this:

find . -type f \( -name "*\.txt" -o -name "*\.pdf" \) -print | awk -F . '{print $NF}' | sort | uniq -c | sort -n

The last sort -n lists the extensions in increasing order.

Nic3500
  • 8,144
  • 10
  • 29
  • 40