我有一个file
,看起来像这样:
header,d0,d1,d2,d3, ...
s1,0,5,2,8, ...
s2,0,8,2,4, ...
s3,0,7,3,4, ...
s4,0,3,2,1, ...
...
我想删除所有带有全零的列,例如d0
我可以手动检查全零的列并找到d0并执行
cut -d "," -f 1,3- file> file_revised
所需的输出是
header,d1,d2,d3, ...
s1,5,2,8, ...
s2,8,2,4, ...
s3,7,3,4, ...
s4,3,2,1, ...
...
但是因为我有很多列,所以很难手动检查。
如何自动删除全零的列?
谢谢。
答案 0 :(得分:2)
提供了第一列不包含全零的功能,这个awk脚本应该可以完成工作
awk -F',' '(NR==FNR && NR >1){for(i = 1; i <= NF; i++)
{a[i] = a[i]+$i}}
(FNR!=NR){out=$1
for(i = 2; i<= NF; i++){
if(a[i]!=0){out=out","$i}
}
print out
}' file_name file_name
请注意,sript将输入文件名file_name两次!
例如,对于输入:
header,d0,d
s1,0,5,2,8,
s2,0,8,2,4,
s3,0,7,3,4,
s4,0,3,2,1,
脚本将作为输出产生
header,d
s1,5,2,8
s2,8,2,4
s3,7,3,4
s4,3,2,1
答案 1 :(得分:2)
这里是一种收集字段以打印到变量(p="$1,$3"
等)并使用system
来调用awk到print p
的人:
$ awk '
BEGIN { FS=OFS="," }
NR==1 {
for(i=1;i<=NF;i++) # gather all field numbers to c[]
c[i]
next }
{
for(i in c) # test all fields that still are all zeros
if($i!=0)
delete c[i] }
END { # after testing all the records
for(i=1;i<=NF;i++)
if(!(i in c))
p=p (p==""?"":OFS) "$" i # make list of list of fields to print
p="print " p # p="print $1,$3,$4,$5,$6"
system("awk \047BEGIN{FS=OFS=\",\"}{" cmd "}\047 " FILENAME)
}' file
输出:
header,d1,d2,d3, ...
s1,5,2,8, ...
s2,8,2,4, ...
s3,7,3,4, ...
s4,3,2,1, ...
如果所有字段均为零,则p="print"
并打印出整个文件。
答案 2 :(得分:1)
$ cat file
header,d0,d1,d2,d3
s1,0,5,2,8
s2,0,8,2,4
s3,0,7,3,4
s4,0,3,2,1
$
$ cat tst.awk
NR==1 {
for (i=1; i<=NF; ++i)
a[i]
next
}
NR==FNR {
for (i in a)
if ($i != "0")
delete a[i]
next
}
{
sep = ""
out = ""
for (i=1; i<=NF; ++i) {
if (i in a)
continue
out = out sep $i
sep = FS
}
print out
}
$
$ awk -F, -f tst.awk file file
header,d1,d2,d3
s1,5,2,8
s2,8,2,4
s3,7,3,4
s4,3,2,1
答案 3 :(得分:0)
也许您可以使用sed
命令,如下所示:
$ sed 's/\b0\,\b//g' test.txt
header,d0,d1,d2,d3
s1,5,2,8
s2,8,2,4
s3,7,3,4
s4,3,2,1
答案 4 :(得分:0)
使用Perl
> cat sumin.txt
header,d0,d1,d2,d3
s1,0,5,2,8
s2,0,8,2,4
s3,0,7,3,4
s4,0,3,2,1
> cat rem_zero.sh
perl -F, -lane '
@FH=@F if $.==1;
if($.>1)
{
$F[$_] and $nz[$_]||=1 for 0..$#F;
push(@L,[@F]);
}
END {
@cols = grep $nz[$_], 0..$#nz;
print join(",",@FH[@cols]);
for my $line (@L) { print "@{$line}[@cols]" }
}
' $1
> rem_zero.sh sumin.txt
header,d1,d2,d3
s1 5 2 8
s2 8 2 4
s3 7 3 4
s4 3 2 1
>