How can I find out how many lines a text file contains without viewing it?
Indeed there is. It is called wc
, originally for word count, I believe, but it can do lines, words, characters, bytes (and with some implementations, the length in bytes of the longest line or the display width of the widest one). The -l
option tells it to count lines (in effect, it counts the newline characters, so only properly delimited lines):
wc -l mytextfile
Or to only output the number of lines:
wc -l < mytextfile
(beware that some implementations insert blanks before that number).
Another option would be to use grep
to find the number of times a pattern is matched:
grep --regexp="$" --count /path/to/myfile.txt
In this example,
$
is an expression that evaluates to a new line (enter button is pressed)--count
suppresses normal output of matches, and displays the number of times it was matched.- The
/path/to/myfile.txt
is pretty obvious, I hope :)
EDIT: As mentioned by @hesse in the comments, this can be shortened to
grep -c $ path/to/file
Which would also make it standard and portable to non-GNU grep
implementations.
I would also add that it is quite easy to do this in pure awk
if you, for some reason, wished to not use wc
.
$ awk 'END { print NR }' /path/to/file
The above print
s the number of records (NR
) present in the file at /path/to/file
.
Note: unlike wc
, this will not print the name of the file. So, if you only wanted the number, this would be a good alternative to cat file | wc -l
.