Concatenate multiple files but include filename as section headers

前端 未结 20 1617
粉色の甜心
粉色の甜心 2020-12-12 09:08

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 fi

相关标签:
20条回答
  • 2020-12-12 09:32

    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

    0 讨论(0)
  • 2020-12-12 09:32
    • 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.

    0 讨论(0)
  • 2020-12-12 09:33

    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 ...
    
    0 讨论(0)
  • 2020-12-12 09:34

    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.

    0 讨论(0)
  • 2020-12-12 09:36

    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.

    0 讨论(0)
  • 2020-12-12 09:36

    And the missing awk solution is:

    $ awk '(FNR==1){print ">> " FILENAME " <<"}1' *
    
    0 讨论(0)
提交回复
热议问题