Concatenate multiple files but include filename as section headers

UnixHeaderTerminalConcatenationCat

Unix Problem Overview


I would like to concatenate a number of text files into one large file in terminal. I know I can do this using the cat command. However, I would like the filename of each file to precede the "data dump" for that file. Anyone know how to do this?

what I currently have:

file1.txt = bluemoongoodbeer

file2.txt = awesomepossum

file3.txt = hownowbrowncow

cat file1.txt file2.txt file3.txt

desired output:

file1

bluemoongoodbeer

file2

awesomepossum

file3

hownowbrowncow

Unix Solutions


Solution 1 - Unix

Was looking for the same thing, and found this to suggest:

tail -n +1 file1.txt file2.txt file3.txt

Output:

==> file1.txt <==
<contents of file1.txt>

==> file2.txt <==
<contents of file2.txt>

==> file3.txt <==
<contents of file3.txt>

If there is only a single file then the header will not be printed. If using GNU utils, you can use -v to always print a header.

Solution 2 - Unix

I used grep for something similar:

grep "" *.txt

It does not give you a 'header', but prefixes every line with the filename.

Solution 3 - Unix

This should do the trick as well:

find . -type f -print -exec cat {} \;

Means:

find    = linux `find` command finds filenames, see `man find` for more info
.       = in current directory
-type f = only files, not directories
-print  = show found file
-exec   = additionally execute another linux command
cat     = linux `cat` command, see `man cat`, displays file contents
{}      = placeholder for the currently found filename
\;      = tell `find` command that it ends now here

You further can combine searches trough boolean operators like -and or -or. find -ls is nice, too.

Solution 4 - Unix

This should do the trick:

for filename in file1.txt file2.txt file3.txt; do
    echo "$filename"
    cat "$filename"
done > output.txt

or to do this for all text files recursively:

find . -type f -name '*.txt' -print | while read filename; do
    echo "$filename"
    cat "$filename"
done > output.txt

Solution 5 - Unix

When there is more than one input file, the more command concatenates them and also includes each filename as a header.

To concatenate to a file:

more *.txt > out.txt

To concatenate to the terminal:

more *.txt | cat

Example output:

::::::::::::::
file1.txt
::::::::::::::
This is
my first file.
::::::::::::::
file2.txt
::::::::::::::
And this is my
second file.

Solution 6 - Unix

find . -type f -print0 | xargs -0 -I % sh -c 'echo %; cat %'

This will print the full filename (including path), then the contents of the file. It is also very flexible, as you can use -name "expr" for the find command, and run as many commands as you like on the files.

Solution 7 - Unix

And the missing awk solution is:

$ awk '(FNR==1){print ">> " FILENAME " <<"}1' *

Solution 8 - Unix

This is how I normally handle formatting like that:

for i in *; do echo "$i"; echo ; cat "$i"; echo ; done ;

I generally pipe the cat into a grep for specific information.

Solution 9 - Unix

I like this option

for x in $(ls ./*.php); do echo $x; cat $x | grep -i 'menuItem'; done

Output looks like this:

./debug-things.php
./Facebook.Pixel.Code.php
./footer.trusted.seller.items.php
./GoogleAnalytics.php
./JivositeCode.php
./Live-Messenger.php
./mPopex.php
./NOTIFICATIONS-box.php
./reviewPopUp_Frame.php
            $('#top-nav-scroller-pos-<?=$active**MenuItem**;?>').addClass('active');
            gotTo**MenuItem**();
./Reviews-Frames-PopUps.php
./social.media.login.btns.php
./social-side-bar.php
./staticWalletsAlerst.php
./tmp-fix.php
./top-nav-scroller.php
$active**MenuItem** = '0';
        $active**MenuItem** = '1';
        $active**MenuItem** = '2';
        $active**MenuItem** = '3';
./Waiting-Overlay.php
./Yandex.Metrika.php

Solution 10 - Unix

you can use this simple command instead of using a for loop,

ls -ltr | awk '{print $9}' | xargs head

Solution 11 - Unix

If the files all have the same name or can be matched by find, you can do (e.g.):

find . -name create.sh | xargs tail -n +1

to find, show the path of and cat each file.

Solution 12 - Unix

If you like colors, try this:

for i in *; do echo; echo $'\e[33;1m'$i$'\e[0m'; cat $i; done | less -R

or:

tail -n +1 * | grep -e $ -e '==.*'

or: (with package 'multitail' installed)

multitail *

Solution 13 - Unix

Here is a really simple way. You said you want to cat, which implies you want to view the entire file. But you also need the filename printed.

Try this

head -n99999999 * or head -n99999999 file1.txt file2.txt file3.txt

Hope that helps

Solution 14 - Unix

If you want to replace those ugly ==> <== with something else

tail -n +1 *.txt | sed -e 's/==>/\n###/g' -e 's/<==/###/g' >> "files.txt"

explanation:

tail -n +1 *.txt - output all files in folder with header

sed -e 's/==>/\n###/g' -e 's/<==/###/g' - replace ==> with new line + ### and <== with just ###

>> "files.txt" - output all to a file

Solution 15 - Unix

find . -type f -exec cat {} \; -print

Solution 16 - Unix

If you want the result in the same format as your desired output you can try:

for file in `ls file{1..3}.txt`; \
do echo $file | cut -d '.' -f 1; \ 
cat $file  ; done;

Result:

file1
bluemoongoodbeer
file2
awesomepossum
file3
hownowbrowncow

You can put echo -e before and after the cut so you have the spacing between the lines as well:

$ for file in `ls file{1..3}.txt`; do echo $file | cut -d '.' -f 1; echo -e; cat $file; echo -e  ; done;

Result:

file1

bluemoongoodbeer

file2

awesomepossum

file3

hownowbrowncow

Solution 17 - Unix

  • AIX 7.1 ksh

... glomming onto those who've already mentioned head works for some of us:

$ r head
head file*.txt
==> file1.txt <==
xxx
111

==> file2.txt <==
yyy
222
nyuk nyuk nyuk

==> file3.txt <==
zzz
$

My need is to read the first line; as noted, if you want more than 10 lines, you'll have to add options (head -9999, etc).

Sorry for posting a derivative comment; I don't have sufficient street cred to comment/add to someone's comment.

Solution 18 - Unix

This method will print filename and then file contents:

tail -f file1.txt file2.txt

Output:

==> file1.txt <==
contents of file1.txt ...
contents of file1.txt ...

==> file2.txt <==
contents of file2.txt ...
contents of file2.txt ...

Solution 19 - Unix

For solving this tasks I usually use the following command:

$ cat file{1..3}.txt >> result.txt

It's a very convenient way to concatenate files if the number of files is quite large.

Solution 20 - Unix

First I created each file: echo 'information' > file1.txt for each file[123].txt.

Then I printed each file to makes sure information was correct: tail file?.txt

Then I did this: tail file?.txt >> Mainfile.txt. This created the Mainfile.txt to store the information in each file into a main file.

cat Mainfile.txt confirmed it was okay.

==> file1.txt <== bluemoongoodbeer

==> file2.txt <== awesomepossum

==> file3.txt <== hownowbrowncow

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNickView Question on Stackoverflow
Solution 1 - UnixDS.View Answer on Stackoverflow
Solution 2 - UnixTheoView Answer on Stackoverflow
Solution 3 - UnixMaxim_unitedView Answer on Stackoverflow
Solution 4 - UnixChris EberleView Answer on Stackoverflow
Solution 5 - UnixSteinfadtView Answer on Stackoverflow
Solution 6 - UnixKevinView Answer on Stackoverflow
Solution 7 - UnixkvantourView Answer on Stackoverflow
Solution 8 - UnixMorpheousMartyView Answer on Stackoverflow
Solution 9 - Unixch3ll0v3kView Answer on Stackoverflow
Solution 10 - UnixGaganView Answer on Stackoverflow
Solution 11 - UnixdrkvogelView Answer on Stackoverflow
Solution 12 - UnixsjasView Answer on Stackoverflow
Solution 13 - UnixTrey BristerView Answer on Stackoverflow
Solution 14 - UnixboroborisView Answer on Stackoverflow
Solution 15 - Unixuser5689319View Answer on Stackoverflow
Solution 16 - UnixFekete SumérView Answer on Stackoverflow
Solution 17 - UnixJustinKaisseView Answer on Stackoverflow
Solution 18 - UnixserenesatView Answer on Stackoverflow
Solution 19 - UnixIgorView Answer on Stackoverflow
Solution 20 - UnixJohn RayView Answer on Stackoverflow