Ever wanted to find out quickly the number of rows and/or columns in file directly from terminal. There are many ways to skin this cat. Here is what I used for number of rows for quite a while:
What about number of columns? "Easy", just combine head and awk commands:
not a big problem (there are likely better ways to do this), but is long and tedious.
I got sick of typing commands above and assembled them in three easy to use function with R-like names: nrow, ncol, and dim. Functions are simply a collection of above ideas and assume that the file is of "rectangular shape", i.e., a table, a matrix, etc.
dim()
{
for FILE in $@; do
NROW=$(nrow $FILE | awk '{ print $1}')
NCOL=$(ncol $FILE | awk '{ print $1}')
echo "$NROW $NCOL $FILE"
unset NROW NCOL
done
}
export -f dim
nrow ()
{
for FILE in $@; do
wc -l $FILE
done
}
export -f nrow
ncol ()
{
for FILE in $@; do
TMP=$(head $FILE -n 1 | awk '{ print NF }')
echo "$TMP $FILE"
unset TMP
done
}
export -f ncol
Add these files to your .bashrc or .profile or something similar and you can now simply type:
nrow filename
ncol filename
dim filename
A simple test:
touch file.txt
echo "line1 with four columns" >> file.txt
echo "line2 with four columns" >> file.txt
nrow file.txt
2 file.txt
ncol file.txt
4 file.txt
dim file.txt
2 4 file.txt