问题
I have a few csv files that I need processing if the number of columns is 4 througout the file
file_1 :
1,aa,bb,cc
2,dd,ee,ff
3,gg,hh,ii
file_2 :
1,xx
2,yy
3,zz
4,xy
I'm using awk for this
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
- Doesn't involve a subshell
- Checks for number of columns throughout the file
- Performs better than the above code (if possible)
回答1:
You may use:
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
This awk
exits with 1
as soon it finds a record with no of columns not equal to 4
.
回答2:
Solution 1st: If you want to check that any line is NOT having 4 fields and move to next file then following may help you on same.
awk -F, 'NF!=4{nextfile} 1' File_*
Solution 2nd: In case you want to skip only those lines which are NOT having 4 fields then following may help you on same.
awk -F, 'NF!=4{next} 1' File_*
来源:https://stackoverflow.com/questions/49130135/check-if-the-file-has-given-number-of-columns