Classic use-cases:
Count lines of a single file
Count result of an input behind a pipe (|)
Complexity::white_check_mark: | Efficiency::white_check_mark: |
---|---|
The classic method: |
wc -l <file>
wc
command, if only the lines count is needed you can just redirect the input:
wc -l < <file>
To suppress the file name, many unefficient variant exist:
wc -l <file> | cut -d ' ' -f 1
wc -l <file> | cut -d' ' -f1
wc -l <file> | awk '{print $1}'
wc -l <file> | sed 's/ .*//'
wc -l <file> | sed 's/ .*$//'
wc <file> | tr -s ' ' | cut -d ' ' -f 2
wc <file> | tr -s ' ' | cut -d' ' -f2
wc <file> | awk '{print $1}'
wc <file> | tr --squeeze-repeats ' ' | cut --delimiter=' ' --fields=2
wc <file> | awk '{print $1}'
In these command one or more process are created to execute these commands.
Complexity::warning::warning: | Efficiency::white_check_mark: |
---|
sed --version
or man sed
to see which version of sed is installed.
sed -n '$=' <file>
Input variant:
sed -n '$=' < <file>
Complexity::warning: | Efficiency::white_check_mark: |
---|
awk 'END {print NR}' <file>
Syntax variant:
awk '{ lineNumber++ } END {print lineNumber}'
Input variant:
awk 'END {print NR}' < <file>
Complexity::warning: | Efficiency::warning: |
---|
grep -c "" <file>
Argument syntax variants:
grep --count "" "${sourceFile}"
Input variant:
grep -c "" < <file>
Complexity::warning: | Efficiency::warning: |
---|
egrep -c "" <file>
Argument syntax variants:
egrep --count "" "${sourceFile}"
Input variant:
egrep -c "" < <file>
Complexity::warning: | Efficiency::white_check_mark: |
---|
perl -lne 'END { print $. }' <file>
Argument syntax variants:
perl -lne'END { print $. }' <file>
Input variant:
perl -lne 'END { print $. }' < <file>
Complexity::warning: | Efficiency::warning::warning: |
---|
Loop and read one line of the file to count it.
typeset -i lineNumber=0
while read line
do
(( lineNumber ++ ))
done < <file>
echo "${lineNumber}"
Interpreted shell script is less efficient than a single command.
Script variant using a file descriptor opened on the input file:
typeset -i lineNumber=0
exec 3< <file>
while read line <&3
do
(( lineNumber ++ ))
done
exec 3<&-
echo "${lineNumber}"
Interpreted shell script is less efficient than a single command.
Script variant using a file descriptor opened on the input file:
typeset -i lineNumber=0
exec 3< <file>
while true
do
read line <&3
if [[ "${?}" -ne 0 ]]
then
break
fi
(( lineNumber ++ ))
done
exec 3<&-
echo "${lineNumber}" > "${targetFile}"
A test is needed after each line read which is inefficient.