Search code examples
linuxshellubuntuterminalwc

Sorting after using wc on files from a directory


Specify a command / set of commands that displays the number of lines of code in the .c and .h files in the current directory, displaying each file in alphabetical order followed by: and the number of lines in the files, and finally the total of the lines of code. . An example that might be displayed would be:

main.c: 202
util.c: 124
util.h: 43
TOTAL: 369

After many attempts, my final result of a one-liner command was :

wc -l *.c *.h | awk '{print $2 ": " $1}' | sed "$ s/total/TOTAL/g"

The problem is that i don't know how to sort them alphabetically without moving the TOTAL aswell (considering we don't know how many files are in that folder). I'm not sure if the command above is that efficient so if you have a better one you can include more variations of it.


Solution

  • perhaps easier would be to sort the input arguments to wc -- perhaps something like this:

    $ find . -maxdepth 1 '(' -name '*.py' -o -name '*.md' ')' | sort | xargs -d'\n' wc -l | awk '{print $2": "$1}' | sed 's/^total:/TOTAL:/'
    ./__main__.py: 70
    ./README.md: 96
    ./SCREENS.md: 76
    ./setup.py: 2
    ./t.py: 10
    TOTAL: 254
    

    note that I use xargs -d'\n' to avoid filenames with spaces in them (if I were targetting GNU+ I would drop the . from find . and perhaps use -print0 | sort -z | xargs -0 instead)