Awk 基于特定列上的数据将数据文件划分为新文件

Awk 基于特定列上的数据将数据文件划分为新文件,awk,Awk,我有一个数据文件(data.txt),如下所示: 0 25 10 25000 1 25 7 18000 1 25 9 15000 0 20 9 1000 1 20 8 800 0 20 8 900 0 50 10 4000 0 50 5 2500 1 50 10 5000 我想将第二列中具有相同值的行复制到单独的文件中。我想获得以下三个文件: data.txt_25 0 25 10 25000 1 25 7 1

我有一个数据文件(data.txt),如下所示:

0  25  10  25000
1  25  7   18000
1  25  9   15000

0  20  9   1000
1  20  8   800
0  20  8   900

0  50  10  4000
0  50  5   2500
1  50  10  5000
我想将第二列中具有相同值的行复制到单独的文件中。我想获得以下三个文件:

data.txt_25

0  25  10  25000
1  25  7   18000
1  25  9   15000
data.txt_20

0  20  9   1000
1  20  8   800
0  20  8   900
data.txt_50

0  50  10  4000
0  50  5   2500
1  50  10  5000
我刚刚开始学习awk。我尝试了以下bash脚本:

  1 #!/bin/bash
  2 
  3 for var in 20 25 50
  4 do
  5         awk -v var="$var" '$2==var { print $0 }' data.txt > data.txt_$var
  6 done
虽然bash脚本执行了我希望它执行的操作,但它非常耗时,因为我必须手动将第二列数据的值放入第3行

所以我想用awk来做这个。如何使用awk实现这一点


提前感谢。

请您尝试以下内容,这考虑到您的第二列数字不是按顺序排列的

sort -k2 Input_file | 
awk '
prev!=$2{
  close(output_file)
  output_file="data.txt_"$2
}
{
  print > (output_file)
  prev=$2
}'
如果输入文件的第2列已排序,则无需使用排序,您可以直接使用,如:

awk '
prev!=$2{
  close(output_file)
  output_file="data.txt_"$2
}
{
  print > (output_file)
  prev=$2
}' Input_file
说明:为上述内容添加详细说明

sort -k2 Input_file |            ##Sorting Input_file with respect to 2nd column then passing output to awk
awk '                            ##Starting awk program from here.
prev!=$2{                        ##Checking if prev variable is NOT equal to $2 then do following.
  close(output_file)             ##Closing output_file in back-end to avoid "too many files opened" errors.
  output_file="data.txt_"$2      ##Creating variable output_file to data.txt_ with $2 here.
}
{
  print > (output_file)          ##Printing current line to output_file here.
  prev=$2                        ##Setting variable prev to $2 here.
}'

对于给定的示例,您还可以使用:

awk -v RS= '{f = "data.txt_" $2; print > f; close(f)}' data.txt
  • -v RS=
    段落模式,空行用于分隔输入记录
  • 使用第二列值构造文件名(默认情况下,awk在空格/制表符/换行符上拆分输入记录)
  • print>f
    将输入记录内容写入文件名
  • 关闭(f)
    关闭文件

因此,我们鼓励用户添加他们为解决自己的问题所付出的努力,因此请在您的问题中添加同样的努力,然后让我们知道。感谢您的回答。如果您能解释一下您的答案,我将非常高兴。@physu,现在补充了详细的解释,请检查一下,让我知道这里是否有任何疑问。