Concatenating multiple text files into a single file in Bash

前端 未结 12 1563
眼角桃花
眼角桃花 2020-11-29 15:31

What is the quickest and most pragmatic way to combine all *.txt file in a directory into one large text file?

Currently I\'m using windows with cygwin so I have acc

相关标签:
12条回答
  • 2020-11-29 16:04

    Be careful, because none of these methods work with a large number of files. Personally, I used this line:

    for i in $(ls | grep ".txt");do cat $i >> output.txt;done
    

    EDIT: As someone said in the comments, you can replace $(ls | grep ".txt") with $(ls *.txt)

    EDIT: thanks to @gnourf_gnourf expertise, the use of glob is the correct way to iterate over files in a directory. Consequently, blasphemous expressions like $(ls | grep ".txt") must be replaced by *.txt (see the article here).

    Good Solution

    for i in *.txt;do cat $i >> output.txt;done
    
    0 讨论(0)
  • 2020-11-29 16:05
    type [source folder]\*.[File extension] > [destination folder]\[file name].[File extension]
    

    For Example:

    type C:\*.txt > C:\1\all.txt
    

    That will Take all the txt files in the C:\ Folder and save it in C:\1 Folder by the name of all.txt

    Or

    type [source folder]\* > [destination folder]\[file name].[File extension]
    

    For Example:

    type C:\* > C:\1\all.txt
    

    That will take all the files that are present in the folder and put there Content in C:\1\all.txt

    0 讨论(0)
  • 2020-11-29 16:08

    You can do like this: cat [directory_path]/**/*.[h,m] > test.txt

    if you use {} to include the extension of the files you want to find, there is a sequencing problem.

    0 讨论(0)
  • 2020-11-29 16:09

    This appends the output to all.txt

    cat *.txt >> all.txt
    

    This overwrites all.txt

    cat *.txt > all.txt
    
    0 讨论(0)
  • 2020-11-29 16:11

    the most pragmatic way with the shell is the cat command. other ways include,

    awk '1' *.txt > all.txt
    perl -ne 'print;' *.txt > all.txt
    
    0 讨论(0)
  • 2020-11-29 16:13

    When you run into a problem where it cats all.txt into all.txt, You can try check all.txt is existing or not, if exists, remove

    Like this:

    [ -e $"all.txt" ] && rm $"all.txt"

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