It is known that programs with graphical interface are more convenient to use, because they are designed for high requirements, plus the terminal allows you to solve certain tasks much faster. So there is a utility wc, it can count the number of lines in a file. The number of lines does not tell much, but in the case when several commands are combined, you can count the lines, taking into account the necessary parameters. How to count lines in a Linux file? Let's highlight a couple of simple but effective examples of using grep, sed and awk commands.
We have already looked at the WC command, now we should familiarize ourselves with one of its key parameters -l
. It counts transitions to a new line, that is, the entire line is counted, including empty lines. The command copes with the task faster than all the others, but only certain strings are possible - with a given condition.
$ wc -l name_file
$ grep -c $ name_file
$ sed -n $= name_file
$ awk 'END{ print NR }' name_file
As we can see, the result is the same, but the wc command took less time to accomplish the task. The other commands are applicable for complex queries. The grep command allows you to find strings with text only: grep -c 'text' file_name
.
$ grep -c 'text' file_name
The grep command handles regular expressions, so you can combine multiple AND, OR, NOT conditions.
When sed performs text processing, but it is much easier to perform a final line count with the wc command. You can delete all lines that are less than three characters long. and complex cases are counted without comments.
$ sed -r '/^.{,3}$/d' file_name | wc -l
If the task is simple. it can be accomplished in other ways. The awk command will be simpler and easier to understand.
$ awk 'length >3' file_name | wc -l
For a visual example of how the awk command works, let's perform string counting while searching for the required value in the csv table file.
In the example, let's count the number of rows with the value of the second parameter more than 50.
$ awk '$2+0 > 50' file_name | wc -l
Add 0 to the expression to remove all non-numeric expressions.