我需要将文件拆分为唯一的文件名。
我可以使用sed
命令来完成此操作,例如, sed -n '/scaffold135_/w 135-scaf.txt' input file.txt
但这很耗时,所以我需要一种聪明的方法来更快地完成它。下面是一个输入示例(原始文件有一百万行):
scaffold1_115,T,N,N,N,N,A,N,N,N,N,N,N,T,N,T,T,N,A,A,N,N,A
scaffold1_123,A,N,N,N,N,G,N,N,N,N,N,N,A,N,A,A,N,G,G,N,N,G
scaffold1_140,C,N,N,N,N,C,N,N,N,N,N,N,C,N,C,C,N,T,C,N,N,C
scaffold2_161,G,N,N,N,N,G,N,C,N,N,C,N,G,N,G,G,N,G,G,C,N,G
scaffold2_162,C,N,N,N,N,C,N,T,N,N,T,N,C,N,C,C,N,C,C,T,N,C
scaffold2_180,C,N,N,N,N,C,N,T,N,N,C,C,C,T,C,C,T,C,C,C,N,C
scaffold2_194,C,N,N,C,N,C,C,C,C,C,C,C,C,C,T,C,C,C,C,C,N,C
scaffold3_195,G,N,N,G,G,C,G,G,G,G,G,G,C,G,C,G,G,C,C,G,N,C
scaffold3_234,T,N,A,T,A,A,T,T,T,A,T,A,A,T,A,A,T,A,A,T,N,A
scaffold101_282,C,T,T,T,C,C,T,C,T,C,C,C,C,T,C,C,T,C,C,C,N,C
scaffold101_371,T,T,T,T,T,C,T,T,T,T,T,T,T,T,T,T,T,T,T,T,N,C
scaffold101_372,T,T,T,T,C,C,T,T,T,T,T,T,T,T,T,T,T,T,T,T,N,C
线条很独特。我希望将每个特定的行scafold
放入一个单独的文件中,例如将所有以 开头的行scaffold1_
放入名为的文件中scaffold1.txt
,依此类推,直到scaffold10156.txt
包含以scaffold10156_
答案1
你应该能够使用重定向和awk
awk -F'_' '{print > $1".txt"}' file
如果共享前缀的行scaffoldn_
是连续的,您可以执行以下操作以避免违反打开文件句柄限制
awk -F'_' 'NR == 1 || $1 != prev{if (f) close(f);f=$1".txt"; prev=$1};
{print > f};END{if (f) close(f)}' file
答案2
为了GNU sed:
sed 's/scaffold\([0-9]*\)_.*/echo "&" >> "\1-scaf.txt"/e' infile