如何从目录中的所有文件中剪切列并创建具有相同名称的新文件?
How to cut columns from all files in a directory and make new files with the same names?
我在一个目录下有32个文件。
每个文件的格式如下-
Sample geneA geneB
Name countsA countsB
我想剪切前两列并将它们粘贴到 geneA 的 32 个文件中,第一和第三列粘贴到 geneB 的文件中。
我尝试的是cut -f1,2 * > *_geneA.txt
,其中输出中的*
被当作一个字符。有没有办法一次搞定?
提前致谢。
这个 GNU awk 程序(参见评论中@EdMorton 的评论)从第一条记录中获取目标文件字段名,根据文件名和字段名创建文件并向其附加字段。在下面的示例中,我在文件 file1
和 file2
:
中两次使用了您的示例数据
$ awk '
FNR==1 { # first record of each file
for(i=2;i<=NF;i++) # iterate field names
f[i]=$i # and hash them to f
}
{ # for all records
for(i=2;i<=NF;i++) { # iterate all but first field
file=FILENAME "_" f[i] ".txt" # form the file name
print ,$i > file # and print to it
}
}' file1 file2
让我们看看做了什么:
$ ls -rt | tail -n 4
file1_geneB.txt
file1_geneA.txt
file2_geneB.txt
file2_geneA.txt
让我们看看里面的一个:
$ cat file1_geneA.txt
Sample geneA
Name countsA
我在一个目录下有32个文件。
每个文件的格式如下-
Sample geneA geneB
Name countsA countsB
我想剪切前两列并将它们粘贴到 geneA 的 32 个文件中,第一和第三列粘贴到 geneB 的文件中。
我尝试的是cut -f1,2 * > *_geneA.txt
,其中输出中的*
被当作一个字符。有没有办法一次搞定?
提前致谢。
这个 GNU awk 程序(参见评论中@EdMorton 的评论)从第一条记录中获取目标文件字段名,根据文件名和字段名创建文件并向其附加字段。在下面的示例中,我在文件 file1
和 file2
:
$ awk '
FNR==1 { # first record of each file
for(i=2;i<=NF;i++) # iterate field names
f[i]=$i # and hash them to f
}
{ # for all records
for(i=2;i<=NF;i++) { # iterate all but first field
file=FILENAME "_" f[i] ".txt" # form the file name
print ,$i > file # and print to it
}
}' file1 file2
让我们看看做了什么:
$ ls -rt | tail -n 4
file1_geneB.txt
file1_geneA.txt
file2_geneB.txt
file2_geneA.txt
让我们看看里面的一个:
$ cat file1_geneA.txt
Sample geneA
Name countsA