Write a short script filecount.sh that counts the total number of files in the current directory with names matching a specified pattern, and print out this number to screen. For example,
bash filecount.sh *.txt
should return the number of .txt files found in the current directory, while
bash filecount.sh p*.txt
should return the number of text files with names starting with p.
1. return the number of .txt files found in the current directory
the script:
#!/bin/bash
START=$HOME
# change your directory to command line if passed
# otherwise use home directory
[ $# -eq 1 ] && START=$1
if [ ! -d $START ]
then
echo "$START not a directory!"
exit 1
fi
# use find command to get all subdirs name in DIRS variable
DIRS=$(find "$START" -type d)
# loop thought each dir to get the number of files in each of
subdir
for d in $DIRS
do
[ "$d" != "." -a "$d" != ".." ] && echo "$d
dirctory has $(ls -l $d | wc -l) files"
done
2. should return the number of text files with names starting with p.
set -- *p* ; echo "$#" # change positional arguments
count=$(printf 'x%.0s' *p*); echo "${#count}" # most shells
printf -v count 'x%.0s' *p*; echo "${#count}" # bash
Get Answers For Free
Most questions answered within 1 hours.