Created
April 10, 2023 07:12
-
-
Save edr3x/5d47b81795fc48314a751a0a5ae58f34 to your computer and use it in GitHub Desktop.
Count number of lines of a file or all files on a folder
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
#!/usr/bin/env bash | |
function count_lines { | |
local file="$1" | |
local lines=$(wc -l < "$file") | |
echo "$lines" | |
} | |
function count_lines_recursive { | |
local dir="$1" | |
local count=0 | |
for file in "$dir"/*; do | |
if [[ -d "$file" ]]; then | |
count=$((count + $(count_lines_recursive "$file"))) | |
elif [[ -f "$file" ]]; then | |
count=$((count + $(count_lines "$file"))) | |
fi | |
done | |
echo "$count" | |
} | |
if [[ $# -ne 1 ]]; then | |
echo "Usage: $0 <file or directory>" | |
exit 1 | |
fi | |
file_or_dir="$1" | |
if [[ -d "$file_or_dir" ]]; then | |
count=$(count_lines_recursive "$file_or_dir") | |
echo "Total number of lines in $file_or_dir: $count" | |
elif [[ -f "$file_or_dir" ]]; then | |
count=$(count_lines "$file_or_dir") | |
echo "Number of lines in $file_or_dir: $count" | |
else | |
echo "Error: $file_or_dir is not a file or directory" | |
exit 1 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment