Thursday, 12 July 2012

Getting number of lines in all files in a directory - Unix

The bash command
 wc -l <file>
will print out the number of lines in <file>.

If you have a collection of files (.csv in the example below), and want to know how many rows are in each file, the command:
 for f in *.csv; do wc -l $f; done  
will print out a list of all the files ending in .csv, along with the number of lines in them.

To print the number of lines, without the filename, the cut command can be used, with the following parameters:
cut -d' ' -f1  

Combining them, we can use:
 for f in *.csv; do wc -l $f |cut -d' ' -f1; done  
to print out just the number of lines in each file ending in .csv in the directory.

2 comments:

  1. Hi,

    nice solution, I figured it might be easier using wc -l *.csv, but you're right.

    But I found another solution:
    wc -l *.cfg|sed -e 's/^[ ]*//'|cut -d" " -f1
    ;)

    cheers

    ReplyDelete
    Replies
    1. Nice solution, I never really think of using sed for this kind of stuff, but it works well!

      Delete

Please leave a comment if you find this blog helpful or interesting! I'd love to hear from you!