我有3个文件,每个文件有4列,我想计算每个文件的列数,然后除以文件总数,从而得到多个文件的平均列数。
note-每个文件的列数可能每次都不相同,文件数量可能会增加。请帮助
eg -
file1 = 3 columns
file2 = 4 columns
file3 = 5 columns
sum(3+4+5)/3(file count)= avg column count for directory having multiple files.
如果您愿意,可以使用下面的代码片段。把每件事都详细解释一下有点费力。
位置包含3个文件
1 #!/bin/bash
2
3 fileCount=`ls -lrt file*.txt | wc -l` ##take the count of number of files in the location
4
5 for file in ./file*.txt; do ##running loop over the list of files individually. "file" is a parameter which'll reppresent each file
6 temp=`awk -F"," '{print NF}' ${file} | uniq` ##storing the column count in "temp" variable. Assumed each row has an entry
7 columnCount=$(($columnCount + $temp)) storing and adding column count from each file
8 done
9
10 avgColumn=$(( columnCount / fileCount )) ##Calculating average
11 echo "Files in directory `pwd` are having ${avgColumn} columns on average!" ##Printing the average