Custom tool for counting lines of Code, i.e. code_counter
Often, when writing code for longer period, some of developers just need to count the code they have written in specific language. Yet, they either have to search on stack overflow. Else more intelligent one’s tend to just use a Unix based command, and assign them an alias. If , you are wondering what is an alias, This is why I am here
Alias is a pseudo name provided by a user, such that by typing that command in command line we essentially execute the command, which is substituted.
Fun Fact:- User defined aliases are global, such that it can execute wherever we want, Example
Now coming back to the script to count code lines by a specific language, or what I call “code_counter”
code_counter is collection of one command which has two parts, explained as follows
- counting lines in a file
- Extracting total number of lines from all files
Counting lines
Unix based command called wc (word count) this command is Unix based, so available in both Linux and Windows.
This command has many uses, which counts words in a file by regex, or number of bytes in a file (essentially useful for .o type files).
Specific usage which we require
wc -l filename/regex
“-l” flag denotes number of lines, Thus only requirement is denote all files of certain type which is a simple regex“ *.<extension>” . Remainder , In a bash script we denote variable by “$”
Thus we obtain,
wc -l *.$1
$1 because the first words after the command is considered. But this is not enough it will give out long list of files with extension supplied in the command, This brings us to second part.
Total number of lines(Sum)
Actually we really don’t need to sum up the Counting lines part already gives us that but at last of the long list. Thus we just need to use grep, some of the Linux users should be familiar with this command. For need to article, It is in most simple terms a “way to adjust outputs from from the stdout”( it does much more). And also something called pipe(i.e. “|”) This is to pipe out the output or to carry the output from one command to another.
Fun Fact:- This “|” is very useful for more things than you would think, even for networks, OS troubleshoots and much more handy applications
Thus for ls command and grep say I want all contains an “i”
“-e” for just the matches to be displayed. Also we can grep a particular word
“grep <word>”
This just shows all matches of word in from some command with pipe.
Putting Pieces together
we get,
“wc -l *.$1 | grep total”
displays total number of lines for the given extension in the command
Finally, the link to the code
After burning the whole brain down.😁😁