Header Ads


How to Count Lines of a File by Command Line

How to Count Lines of a File by Command Line


Need to get the line count of a text file or document? Counting lines of any file is easy at the command line, and the command for line counting is the same in all modern Unix based operating systems, meaning this line counting trick will work the same on Mac OS and Mac OS X, Linux, BSD, and even Windows with Bash shell. For our purposes here we will use the most direct line counting tool available at the command line, wc. The wc utility is able to display line count, as well as reveal word count and character count. Our focus here is of course on the former, so well be showing how to use wc for counting lines of any text file provided as input. wc defines a line as a string of characters delimited by a newline character, meaning only unique new lines will be counted as a line. So if there are no newline characters in a file, and the file is just one enormous sentence or single command string, it would be reported as one line. As you likely guessed, the -l flag (lower case L) is for line. For example, running the wc -l command on a file located on the desktop called exampleFileToCountLines.txt would look like the following: As you can see in this example, the line count of the text file given is 1213, meaning the file is 1,213 lines long. The wc command works the same on any modern Unix based operating system, including Mac OS, Linux, FreeBSD, Windows with Bash, and more. You can also run the wc command without the -l flag, which will then reveal the line count, the word count, and the character count, in that order. Like: Contrast that command output to the same command with wc -l flag only: This is only counting the lines of a text file as input and it does not modify the file at all. If you do wish to modify the file . You can also use wc to count lines of any data piped into it, for example from cat or ls: The output in that scenario will simply be the number of lines in the file, like 9. The wc command is pretty neat, you can for wc to get even more ideas and tricks for usage. This is obviously all geared for the command line, but there are other ways of getting line and character counts of files as well. You can manually count them out for short files, third party Mac apps like BBEdit show line number by default, and if you get the little cousin to BBEdit known as TextWrangler then you can go about too. You can also make a DIY for the Mac as a Service. And if you happen to already know the line number of a file you want to access, you can , though unfortunately TextEdit doesnt show line numbers, which seems like an oversight.


No comments

Powered by Blogger.