When working with multiple files in Linux, the cat
command is our go-to tool for quick file concatenation. However, its default behavior of merging files without visual separation can make it difficult to distinguish where one file ends and another begins.
For a pure Bash solution that doesn't require installing additional packages:
for f in *; do cat "$f"; printf 'XXXXXXXXXXXX\\n'; done
Or using echo
:
for f in *; do cat "$f"; echo "XXXXXXXXXXXX"; done
For better readability and customization:
# With dynamic separators showing filenames
for file in *; do
echo "===== Contents of $file ====="
cat "$file"
echo ""
done
Using awk
for more control:
awk 'FNR==1{if(NR>1) print "XXXXXXXXXXXX";} {print;}' *
Add this to your .bashrc
for a persistent solution:
function catsep() {
for f in "$@"; do
cat "$f"
echo "XXXXXXXXXXXX"
done
}
Now you can simply run:
catsep *
The bat
command (a cat
alternative) provides built-in file separation:
bat --style=header,grid *
When working with multiple files in Linux, the cat
command's default behavior concatenates files without any visual separation between them. This can make it difficult to distinguish where one file ends and another begins, especially when dealing with similar content.
This situation frequently occurs when:
- Reviewing logs from multiple services
- Comparing configuration files
- Examining output from related processes
- Debugging scripts with multiple source files
The most straightforward solution uses a for loop with echo:
for f in *; do cat "$f"; echo -e "\nXXXXXXXXXXXX\n"; done
This will:
- Process each file in the current directory
- Display its contents
- Add a separator line after each file
For more control over the output:
Include Filename Headers
for f in *; do echo -e "\n=== $f ===\n"; cat "$f"; done
Colorized Separators
for f in *; do cat "$f"; echo -e "\n\033[1;31m==========\033[0m\n"; done
Using awk for Better Formatting
awk 'FNR==1 && NR!=1 {print "XXXXXXXXXXXX"} 1' *
This awk command:
- Prints the separator before each new file (except the first)
- Preserves all original file contents
- Handles large files efficiently
For frequent use, create a function in your ~/.bashrc
:
function catsep() { for f in "$@"; do [ -f "$f" ] && cat "$f" && echo -e "\nXXXXXXXXXXXX\n" done }
Usage:
catsep file1 file2 file3
For very large directories or files:
- The awk solution is generally fastest
- Shell loops have more overhead
- Consider
find -exec
for recursive operations