76

Let say I have the program:

Calculate.py

Is there a unix command-line that counts the number of lines outputted from my program, Calculate.py?

MEhsan
  • 863

2 Answers2

123

You can pipe the output in to wc. You can use the -l flag to count lines. Run the program normally and use a pipe to redirect to wc.

python Calculate.py | wc -l

Alternatively, you can redirect the output of your program to a file, say calc.out, and run wc on that file.

python Calculate.py > calc.out
wc -l calc.out
cutrightjm
  • 5,290
  • 4
    It's little things like this that make piping so damn powerful. We'd do ourselves good to bring this interoperability back to software development, which I suppose is what Functional Programming is all about. – Joshua Pinter Oct 27 '18 at 14:26
  • 1
    @JoshuaPinter on the other thand if you just want to pipe the number of lines into another function, you now need to manually parse the output of wc. Mercifully this is easy (cut -f1 -d' '), but the same isn't true for every command. There's something to be said for the Powershell approach of making the command line primitive an "object", rather than a text stream. – shadowtalker Nov 26 '18 at 19:42
  • @shadowtalker I'm not familiar with Powershell but passing objects instead of Strings makes sense. At some point I'd like to dive deep into more command line tooling. – Joshua Pinter Nov 27 '18 at 02:13
1

Above communicate (wc -l) will count the empty lines too. so better to use below command which deletes the empty lines and count it

python Calculate.py |sed '/^$/d'| awk '{print NR}'| sort -nr| sed -n '1p'
  • 2
    Seriously?  sed | awk | sort | sed just to count lines?  (1) sed '/^$/d' can be collapsed into grep -v '^$' or even grep '.'.  (2) Then, to count lines, add -c, so python Calculate.py | grep -c '.'.  (And you don’t even need the quotes around “.”.) – G-Man Says 'Reinstate Monica' Mar 15 '22 at 20:47