2

How would you merge different input .txt and .tsv files (within a directory) who have the same name but a different extension into an output file?


Input: file1.txt, file2.txt, file1.tsv, file2.tsv

Output: file1.merged, file2.merged

2

With zsh:

ext='(txt|tsv|text|log)'
for f (**/*.$~ext(.)) cat < $f >> $f:t:r.merged

The order of merging will be alphabetical within a same directory. That is, a/file.txt will be included before b/file.txt and a/file.log before a/file.txt.

Also note that hidden files (those whose name starts with .) won't be considered (add the D glob qualifier if you want them).

1

cat file1.* > file1.merged

cat file2.* > file2.merged

  • Yes but, I don't have only two extensions per file name (There could be for example something like file1.csv that I'm not willing to merge). Plus, I have a lot of filenames (~100), so a loop would be better. – dovah Nov 10 '15 at 12:38
  • 1
    Exactly, @don_crissti, that's my point. – dovah Nov 10 '15 at 12:40
  • The question says that you're looking to merge all files with the same name but different extension into an output file. This means that if you have a file1.csv in the same directory, it will be merged into the output file. If only *.txt and *.tsv are allowed, then you can instead do cat file1.txt file1.tsv > file1.merged && cat file2.txt file2.tsv > file2.merged As for multiple filenames, you may want to write a script to handle the matrix of which files should be concatenated and which should not. – mkrufky Nov 10 '15 at 12:46
  • Yes, good point. I will edit the question. By the way, I need a loop to look for filenames, I cannot concatenate manually. – dovah Nov 10 '15 at 12:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.