Write a shell script in bash that includes a function that reports the number of
ID: 3869814 • Letter: W
Question
Write a shell script in bash that includes a function that reports the number of files whose names have a given ending, and lists the file names if the number if less than 10. For example, my_funct abc will tell me about all the files that are called something.abc. You only need to handle the files in the current working directory. This script needs to report about files that are called *.jpg, *.html, and *.java. You would need to create some empty files to test your script.
Language features to practice:
variable expansion $
command substitution
function
if
Explanation / Answer
# Usage:
# $ bash ffinder.sh
file_finder() {
# Change the Pattern
# If you don't need any pattern do:
# pattern_to_search = '*'
# Or edit to make it other pattern.
#to skip or replace this filename "as" change with desired variable like
pattern_to_search='as' # it will search for file name having as.html harshasj.html
# File names matching the pattern and having particular file extentions.
# Only file names will be printed without path.
# To make case sensitive, replace -iname with -name.
file_names=`find . -maxdepth 1 -iname *$pattern_to_search* -exec basename {} ; | grep -E '.html|.jpg|.java'`
# Number of files matching the above pattern.
number_of_files=`echo -n "$file_names" | wc -l`
# Printing the number of files.
# echo "Number of files: $number_of_files"
# Checking if the number of files are less than 10.
# If yes, then print the file names.
# else, tell the number.
if [ "$number_of_files" -eq 0 ]
then
echo "No files matched."
elif [ "$number_of_files" -gt 0 ] && [ "$number_of_files" -lt 10 ]
then
echo "Number of files are: $((number_of_files+1))"
echo "File names are:"
echo "$file_names"
else
echo "Number of files are: $number_of_files"
fi
}
# Function call.
file_finder
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.