Bash 如何创建保留具有特定值的列名的文件

Bash 如何创建保留具有特定值的列名的文件,bash,awk,sed,Bash,Awk,Sed,我有一个文件,其中第一列取某些值(在本例中为4) 我想构造3个文件,一个有3列值,一个有2列值,一个有1列值*此外,这些价值之一必须是“产品” file3.txt product,0 0,no way brand,0 0 0,detergent product,0 0 1,sugar negative,0 0 1, sight product,0 0,no way brand,0 0 0,detergent product,0 0 1,sugar product,0 0,no way pro

我有一个文件,其中第一列取某些值(在本例中为4)

我想构造3个文件,一个有3列值,一个有2列值,一个有1列值*此外,这些价值之一必须是“产品”

file3.txt

product,0 0,no way
brand,0 0 0,detergent
product,0 0 1,sugar
negative,0 0 1, sight
product,0 0,no way
brand,0 0 0,detergent
product,0 0 1,sugar
product,0 0,no way
product,0 0 1,sugar
file2.txt

product,0 0,no way
brand,0 0 0,detergent
product,0 0 1,sugar
negative,0 0 1, sight
product,0 0,no way
brand,0 0 0,detergent
product,0 0 1,sugar
product,0 0,no way
product,0 0 1,sugar
file1.txt

product,0 0,no way
brand,0 0 0,detergent
product,0 0 1,sugar
negative,0 0 1, sight
product,0 0,no way
brand,0 0 0,detergent
product,0 0 1,sugar
product,0 0,no way
product,0 0 1,sugar
这个过程能在awk中自动完成吗? 此时,我正在手动创建包含要保留的列名的文件,并使用该文件

awk 'NR==FNR{v[$1]; next} $1 in v' values.txt FS=, datafile
你可以试试

#! /usr/bin/awk -f

BEGIN { FS=","}
{ 
    if (length(w) < m && !($1 in w)) w[$1]=1
    if ($1 in w) print
}
其中
m
是唯一值的数目

编辑 环路


这缺乏一定的优雅,但它是有效的

awk -F, '{
if(!one) one=$1;
if(!two && $1 != one) two=$1;
if(!three && $1 != one && $1 != two) three=$1;

if (one && $1==one) {print $0 > "file1.txt"; print $0 > "file2.txt"; print $0 > "file3.txt";}
if (two && $1==two) {print $0 > "file2.txt"; print $0 > "file3.txt";}
if (three && $1==three) print $0 > "file3.txt";
}' values.txt

它可以用一种更为惯用的方式编写,但这与我提出的逻辑相同。我可以将bash循环与awk混合使用吗?对于百万美元(seq 1100),请做doSomething($m)doneThanks以获得您的回复。我根据自己的需要对这个问题做了一些修改。还有什么方法可以确保我们总是在选择中包含一个特定的列值“product”?将另一个变量传递给脚本,如m,并将该值添加到BEGIN块的数组中我使用了这个bash脚本#/bin/bash(单位:百万美元)(序号150);do./script.awk-vm=$m new_test.csv>文件$mi.txt;完成并获得错误“(FILENAME=new_test.csv FNR=1)致命:尝试将标量'w'用作数组”