From be13887d98e4b6f4039a1056d3b7dd75c20b9418 Mon Sep 17 00:00:00 2001 From: eslopfer Date: Thu, 16 Feb 2023 18:10:32 +0000 Subject: [PATCH] feat(better-cat): add solution for exercise --- sh/tests/solutions/better-cat.sh | 51 ++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 sh/tests/solutions/better-cat.sh diff --git a/sh/tests/solutions/better-cat.sh b/sh/tests/solutions/better-cat.sh new file mode 100644 index 000000000..e7584a512 --- /dev/null +++ b/sh/tests/solutions/better-cat.sh @@ -0,0 +1,51 @@ +#!/bin/bash + +while getopts "clr" opt; do + case $opt in + c) exclude_comments=true;; + l) show_length=true;; + r) show_recap=true;; + *) echo "Usage: $0 [-c] [-l] [-r] [file1] [file2] ..." >&2 + exit 1;; + esac +done + +shift $((OPTIND-1)) + +if [[ $# -eq 0 ]]; then + set -- * +fi + +line_count=0 +char_count=0 + +for file in "$@"; do + if [[ ! -e $file ]]; then + echo "$0: $file: No such file or directory" >&2 + continue + fi + + line_num=0 + while read -r line; do + line_num=$((line_num+1)) + if [[ $exclude_comments && $line == \#* ]]; then + continue + fi + if [[ $show_length ]]; then + echo "$line_num ($(( ${#line} ))): $line" + else + echo "$line_num: $line" + fi + char_count=$((char_count+${#line})) + done < "$file" + + line_count=$((line_count+line_num)) +done + +if [[ $show_recap ]]; then + echo "Total: $line_count lines, $char_count characters" +fi + +if [[ $line_count -eq 0 ]]; then + exit 1 +fi