Concatenate multiple files but include filename as section headers

前端 未结 20 1618
粉色の甜心
粉色の甜心 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:24

    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.

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

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

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

    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.

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

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

    I used grep for something similar:

    grep "" *.txt
    

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

    0 讨论(0)
提交回复
热议问题