How would you write a script in Shell to recursively search for all files with a specific extension in a directory and its subdirectories, and then display the total number of files found?

1 Answers
Answered by suresh

To write a script in Shell to recursively search for all files with a specific extension in a directory and its subdirectories and display the total number of files found, you can use the following script snippet:

```bash
#!/bin/bash

# Define the directory to search
directory="/path/to/directory"
extension=".txt" # Change this to the desired file extension

# Use find command to search for files with the specified extension
file_count=$(find "$directory" -type f -name "*$extension" | wc -l)

# Display the total number of files found
echo "Total number of '$extension' files found in $directory and its subdirectories: $file_count"
```

In the above script, make sure to replace `"/path/to/directory"` with the actual path of the directory you want to search and update `".txt"` to the desired file extension like `".pdf"`, `".doc"`, etc.

To enhance the script for readability and efficiency, you can consider adding error handling, user input validation, or output formatting where necessary.

Using this script in a Shell environment will allow you to efficiently search for files with a specific extension and display the total count, making file management tasks more manageable.

Focus keyword: Shell script to recursively search for files with a specific extension and count them.

Answer for Question: How would you write a script in Shell to recursively search for all files with a specific extension in a directory and its subdirectories, and then display the total number of files found?