Concatenating multiple text files into a single fi

2019-01-07 01:59发布

问题:

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 access to BASH.

Windows shell command would be nice too but I doubt there is one.

回答1:

This appends the output to all.txt

cat *.txt >> all.txt

This overwrites all.txt

cat *.txt > all.txt


回答2:

Just remember, for all the solutions given so far, the shell decides the order in which the files are concatenated. For Bash, IIRC, that's alphabetical order. If the order is important, you should either name the files appropriately (01file.txt, 02file.txt, etc...) or specify each file in the order you want it concatenated.

$ cat file1 file2 file3 file4 file5 file6 > out.txt


回答3:

The Windows shell command type can do this:

type *.txt >outputfile

Type type command also writes file names to stderr, which are not captured by the > redirect operator (but will show up on the console).



回答4:

You can use Windows shell copy to concatenate files.

C:\> copy *.txt outputfile

From the help:

To append files, specify a single file for destination, but multiple files for source (using wildcards or file1+file2+file3 format).



回答5:

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


回答6:

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



回答7:

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") by $(ls *.txt)



回答8:

How about this approach?

find . -type f -name '*.txt' -exec cat {} + >> output.txt


回答9:

all of that is nasty....

ls | grep *.txt | while read file; do cat $file >> ./output.txt; done;

easy stuff.



标签: bash shell