Create a bash script that will get the word count for each chapter in each act, given…
- User
Create a bash script that will get the word count for each chapter in each act, given the file structure ./chapters/act-/chapter-
- Assistant
Sure! Below is a Bash script that will calculate the word count for each chapter in a given directory structure (
./chapters/act-*/chapter-*). The script will iterate through each act and each chapter within that act, counting the words in each chapter file and then displaying the results.Here is the script:
#!/bin/bash # Change to the chapters directory cd ./chapters || { echo "Directory ./chapters not found."; exit 1; } # Iterate through each act directory for act in act-*; do # Check if the directory exists if [[ -d $act ]]; then echo "Processing $act..." # Iterate through each chapter file in the act directory for chapter in "$act"/chapter-*; do # Check if the file exists if [[ -f $chapter ]]; then # Get the word count word_count=$(wc -w < "$chapter") # Get the chapter name without the full path chapter_name=$(basename "$chapter") # Print the result echo "Word count for $chapter_name: $word_count" fi done else echo "No acts found" fi done - User
given this code
book_word_counter_by_chapter() { local total_words=0 echo "Word Count by Chapter:" echo "----------------------" for chapter_dir in ./chapters/act-*/chapter-*; do if [[ -d "$chapter_dir" ]]; then local chapter_words=0 for page_file in "$chapter_dir"/*.md; do if [[ -f "$page_file" ]]; then words=( $(< "$page_file") ) (( chapter_words += ${#words[@]} )) fi done chapter_name=$(basename "$chapter_dir") echo "$chapter_name: $chapter_words words" (( total_words += chapter_words )) fi done echo "----------------------" echo "Total Word Count: $total_words words" }can you print out each act
- Assistant
Certainly! To modify your existing function so that it prints out the word count for each chapter and separates the counts by act, you can introduce an additional loop to track the acts. We'll print the total word counts for each act in a similar way to what you're already doing for chapters. Here's how your modified function would look:
- User
omit "act-" from $act_dir
- Assistant
If you want to omit the "act-" prefix from the act names when displaying the word counts, you can modify the way you output the act name. You can use parameter expansion to remove the "act-" part from the directory name. Here’s how you can adjust the function to achieve that: