Apologies for the oversight. Let's correct that and ensure a blank line is added between the contents of each file. Here’s the revised script:
#!/bin/bash
# Output file
OUTPUT_FILE="merged.txt"
# Check if the output file already exists and remove it
if [ -f "$OUTPUT_FILE" ]; then
rm "$OUTPUT_FILE"
fi
# Merge all .txt files in lexicographical order
for file in *.txt; do
if [ -f "$file" ]; then
# Add a comment line with the file name
echo "//$file" >> "$OUTPUT_FILE"
echo "" >> "$OUTPUT_FILE" # Newline after the comment
# Append the content of the file
cat "$file" >> "$OUTPUT_FILE"
echo "" >> "$OUTPUT_FILE" # Add a blank line between files
fi
done
echo "All text files have been merged into $OUTPUT_FILE"
Explanation of the Fix
- Adding a Blank Line Between Files
echo "" >> "$OUTPUT_FILE" # Add a blank line between files
This line ensures that a blank line is added after the content of each file, providing clear separation between the contents of different files in the merged output.
Running the Script
Save the script as merge_text_files.sh, make it executable, and run it:
chmod +x merge_text_files.sh
./merge_text_files.sh
This will create a merged.txt file where each section starts with a comment line indicating the original filename, followed by the content of that file, and a blank line to separate each file's content.