我有一个像这样的 .txt 文件:
col1 col2 col3 col4
1 3 4 A
2 4 6 B
3 1 5 D
5 3 7 F
Run Code Online (Sandbox Code Playgroud)
我想提取第 1 列之后的每一列 (i),并将第 1 列和第 i 列输出到一个由第 i 列标题命名的新文件中。
这意味着我将拥有三个输出文件,分别名为“col2.reform.txt”、“col3.reform.txt”和“col4.reform.txt”。
例如,输出“col2.reform.txt”文件将如下所示:
col1 col2
1 3
2 4
3 1
5 3
Run Code Online (Sandbox Code Playgroud)
我尝试了这样的代码:
awk '{for (i=1; i <=NF; i++) print $1"\t"$i > ("{awk 'NR==1' $i}"".reform.txt")}' inputfile
Run Code Online (Sandbox Code Playgroud)
显然“{awk 'NR==1' $i}”部分不起作用,我得到了一个名为 {awk 'NR==1' $i}.reform.txt 的文件。
如何正确获取文件名?谢谢!
PS:如何删除终端中的文件“{awk 'NR==1' $i}.reform.txt”?
编辑:上面的列名称只是一个示例。我更喜欢使用提取列名称标题的命令,因为我的文件实际上使用不同的单词作为标题。
根据您显示的示例,您可以尝试以下操作吗?使用 GNU 中显示的示例编写awk。
awk '
FNR==1{
for(i=1;i<=NF;i++){
heading[i]=$i
}
next
}
{
for(i=2;i<=NF;i++){
close(outFile)
outFile="col"i".reform.txt"
if(!indVal[i]++){ print heading[1],heading[i] > (outFile) }
print $1,$i >> (outFile)
}
}
' Input_file
Run Code Online (Sandbox Code Playgroud)
输出文件将使用名称创建,例如--> col2.reform.txt、col3.reform.txt等等col4.reform.txt...
内容样本col2.reform.txt如下:
cat col2.reform.txt
col1 col2
1 3
2 4
3 1
5 3
Run Code Online (Sandbox Code Playgroud)
说明:对上述内容添加详细说明。
awk ' ##Starting awk program from here.
FNR==1{ ##Checking condition if this is first line then do following.
for(i=1;i<=NF;i++){ ##Traversing through all fields of current line.
heading[i]=$i ##Creating heading array with index of i and value of current field.
}
next ##next will skip all further statements from here.
}
{
for(i=2;i<=NF;i++){ ##Traversing from 2nd field to till last field of all rest of lines.
close(outFile) ##Closing outFile to avoid too many opened files error.
outFile="col"i".reform.txt" ##Creating outFile which has output file name in it.
if(!indVal[i]++){ print heading[1],heading[i] > (outFile) }
##Checking condition if i is NOT present in indVal then print 1st element of heading and current element of heading into outFile.
print $1,$i >> (outFile) ##Printing 1st field and current field values to output file here.
}
}
' Input_file ##Mentioning Input_file name here.
Run Code Online (Sandbox Code Playgroud)