Last active
December 8, 2020 15:49
-
-
Save astout/2986de697e9f28702f603827b49266cb to your computer and use it in GitHub Desktop.
List number of lines in a file or in all files in a directory (non-recursive). Data is outputted in neat columns.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# author: Alex Stout | |
# check if the provided argument is a directory | |
if [[ -d $1 ]]; then | |
: # nop -- do nothing | |
elif [[ -f $1 ]]; then # or is it a file | |
: # nop -- do nothing | |
else | |
echo "argument is invalid" | |
exit 1 | |
fi | |
# function will count the number of lines in a file | |
__file_count=0 | |
count_lines_in_file() { | |
local __file=$1 | |
# echo "counting lines in file $__file" | |
__file_count=$(grep -c ^ < "$__file") | |
} | |
# function will count the number of lines of every file in the given directory | |
__dir_count=0 | |
count_lines_in_dir() { | |
local __result=$1 | |
num_files=$(find $1 -type f -maxdepth 1 | wc -l) | |
# echo "number of files: $num_files" | |
i=0 | |
find $1 -type f -maxdepth 1 | while read FILE; do | |
count_lines_in_file $FILE | |
printf '%-15s%-25s%-5s\n' $1 $(basename $FILE) $__file_count | |
((__dir_count = __dir_count + __file_count)) | |
((i = i + 1)) | |
if [[ $num_files -eq $i ]]; then | |
printf '\nTOTAL LINES COUNTED: %s\n' $__dir_count | |
fi | |
done | |
# NOTE: you'd think you could add the total lines to __dir_count and print after the loop or even use the value outside the function, | |
# but it doesn't work! | |
# apparently using the pipe starts a new subprocess so the updates to the variable in that loop do not get applied to the parent process | |
# there's probably some way around it, but I didn't care enough for the immediate use of this script | |
} | |
# Print a header for the data | |
printf '\n%-15s%-25s%-5s\n' 'Directory' 'File' 'Lines' | |
if [[ -d $1 ]]; then | |
count_lines_in_dir $1 | |
elif [[ -f $1 ]]; then | |
count_lines_in_file $1 | |
printf '\nTOTAL LINES COUNTED: %s\n' $__file_count | |
else | |
echo "an error occurred" | |
exit 1 | |
fi | |
echo "" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment