简体   繁体   English

根据部分文件名合并文件

[英]Merge files based on part of file name

I have about 450 csv files in a folder with names in the format (sample names below): 我的文件夹中包含约450个csv文件,其名称格式为(以下示例名称):

1_a.csv 1_a.csv

1_b.csv 1_b.csv

1_c.csv 1_c.csv

... ...

1_h.csv 1_h.csv

2_a.csv 2_a.csv

2_b.csv 2_b.csv

... ...

2_h.csv 2_h.csv

... ...

42_a.csv 42_a.csv

... ...

42_h.csv 42_h.csv

I wish to combine all files of the type "1_xxx.csv" into "1.csv", all files of the format "2_xxx.csv" into "2.csv" and so on. 我希望将“ 1_xxx.csv”类型的所有文件合并为“ 1.csv”,将“ 2_xxx.csv”格式的所有文件合并为“ 2.csv”,依此类推。

I tried using cat but I am only able to merge one set of files at a time. 我尝试使用cat,但一次只能合并一组文件。 Is there a way to run the command in loop in linux? 有没有办法在Linux中循环运行命令? Any Python3 based solutions are also welcome. 也欢迎任何基于Python3的解决方案。

For a python solution the comment provided by mnistic links to a solution. 对于python解决方案,mnistic所提供的注释指向解决方案。 If you want a bash solution you can use the find command with the -exec flag like 如果您想要一个bash解决方案,则可以将find命令与-exec标志一起使用,例如

find . -name "1_*.csv" -exec cat {} >> 1.csv \;

That command should find all the csv files beginning with 1_ and then appending them to the file 1.csv. 该命令应找到所有以1_开头的csv文件,然后将它们附加到文件1.csv。

For more information on find check out https://ss64.com/bash/find.html 有关查找的更多信息,请查看https://ss64.com/bash/find.html

EDIT: For a loop 编辑:循环

for i {1..450}
do
    find . -name "$i_*.csv" -exec cat {} >> $i.csv \;
done

this should work 这应该工作

Source: http://go2linux.garron.me/bash-for-loop/ 来源: http//go2linux.garron.me/bash-for-loop/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM