使用awk

时间:2019-11-01 15:38:23

标签: awk

我有20个文件,我想将每个文件的第一列打印到另一个文件中,我需要20个输出文件。

我尝试了以下命令,但是此命令将所有输出放入一个文件中。

awk '{print $1}' /home/gee/SNP_data/20* > out_file

将输出写入不同的文件,我有20个输入文件

2 个答案:

答案 0 :(得分:1)

第一个解决方案: 。能否请您尝试以下操作。

awk '
FNR==1{
  if(file){
    close(file)
  }
  file="out_file_"FILENAME".txt"
}
{
  print $1 > (file)
}
' /home/gee/SNP_data/20*

说明: 添加上述代码的说明。

awk '                                     ##Starting awk program here.
FNR==1{                                   ##checking condition if FNR==1 then do following.
  if(file){                               ##Checking condition if variable file is NOT NULL then do following.
    close(file)                           ##Using close to close the opened output file in backend, to avoid too many opened files error.
  }                                       ##Closing BLOCK for if condition.
  file="out_file_"FILENAME".txt"          ##Setting variable file value to string out_file_ then FILENAME(which is Input_file) and append .txt to it.
}                                         ##Closing BLOCK for condition for FNR==1 here.
{
  print $1 > (file)                       ##Printing first field to variable file here.
}
' /home/gee/SNP_data/20*                  ##Mentioning Input_file path here to pass files here.


第二个解决方案: :如果您需要获取输出文件,例如output_file_1.txt等等,请尝试以下操作。我创建了一个名为out_file的awk变量,您也可以在其中更改输出文件名的名字首字母(根据需要)。

awk -v out_file="Output_file_" '
FNR==1{
  if(file){
    close(file)
  }
  ++count
  file=out_file count".txt"
}
{
  print $1 > (file)
}
' /home/gee/SNP_data/20*

答案 1 :(得分:1)

Awk具有内置的重定向运算符,您可以像这样使用它:

awk '{ print $1 > ("out_" FILENAME) }' /home/gee/SNP_data/20*

或者甚至更好:

awk 'FNR==1 { close(f); f=("out_" FILENAME) } { print $1 > f }' /home/gee/SNP_data/20*

Former只是重定向操作符的示例用法,后者是如何稳健地使用它。

相关问题