garysimpson.dev
Mobile development with swift and flutter

Fun With Shell File Merging

September 13, 2024 at 2:38PM

It took some doing. A lot of back and forth with ChatGPT. The first attempt created a 1.1GB file with the same text repeating until I manually killed the process using ActivityMonitor.app. With that sorted I was able to edit the script and got is working flawlessly.

Creating Steps:

  • Create the script: (see below or download here)
  • Save the script: (e.g in home folder ~)
  • Give script permissions: chmod +x merge_files_current_dir.sh
  • Run the script (from the dir): ~/merge_files_current_dir.sh



#!/bin/bash

# Get the current directory name
directory_path="."
directory_name=$(basename "$PWD")
output_file="${directory_name}_merged.txt"

# Create or empty the output file (exclude this file from being processed by find)
> "$output_file"

# Loop through all files in the current directory and its subdirectories, excluding the output file
find "$directory_path" -type f ! -name "$output_file" | while read -r file; do
    echo "===== $(basename "$file") =====" >> "$output_file"
    cat "$file" >> "$output_file"
    echo -e "\n" >> "$output_file"
    echo "Copied contents of '$file'"
done

echo "All files merged into '$output_file'"

Happy Coding ;-)