检查文件是否具有给定的列数 [英] Check if the file has given number of columns

查看:80
本文介绍了检查文件是否具有给定的列数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果文件中的列数为4,则我需要处理一些csv文件

I have a few csv files that I need processing if the number of columns is 4 througout the file

文件_1:

1,aa,bb,cc
2,dd,ee,ff
3,gg,hh,ii

file_2:

1,xx
2,yy
3,zz
4,xy

我为此使用awk

for file in file_1 file_2 ... file_n
do
    if [[ `awk -F"," 'NF==4' $file` ]]
    then
        #process
    else
        continue
    fi
done

我正在寻找一种解决方案

I'm looking for a solution that

  • 不涉及subshel​​l
  • 检查整个文件中的列数
  • 性能优于上述代码(如果可能)

推荐答案

您可以使用:

for f in file_1 file_2 file_n; do
   if awk -F, 'NF!=4{exit 1}' "$f"; then
      echo "good $f"
   else
      echo "bad $f"
   fi
done

awk在找到没有列不等于4的记录后立即以1退出.

This awk exits with 1 as soon it finds a record with no of columns not equal to 4.

这篇关于检查文件是否具有给定的列数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆