Skip to content

Comment on Show HN: Pythonpy – the swiss army knife of the command line

Comments

I like it! Now I can count the number of files I have in a directory:

    ls |py -l 'sum(1 for x in l)'
And also I can count the number of files whose names matche a certain extension:
    ls |grep .py |py -l 'sum(1 for x in l)'
I am not saying it was not possible before, but I don't know how to do it in bash.

Looking forward to use that for some basic stats on file. The following should sum up the first column of a csv.

    cat data.csv| py -x 'x[0]' |py -l 'sum(x for x in l)'

You'll probably want to learn the regular unix way as well. Tools like this are nice, but you're already 99% there as it is for most things.

    ls | wc -l

    ls | grep -c .py
(note the cat and pipe are not needed)
    awk -F',' '{sum+=$1}END{print sum}' data.csv

Yea, IMO the best way to do this with pythonpy is:

  py -l 'len(l)'
That being said, I still use wc -l every time. In fact, I always prefer regular unix commands (e.g. grep, xargs, head) to pythonpy when possible. But there are some things, such as:
  py -l 'l[::2]'
which while possible with tools like sed, are just much better expressed with pythonpy.
ls | grep -c .py

That won't work if there are files with names like foo.py.txt.

These will:

ls | grep -c '.py$'

or better, because less names to filter out:

ls -l *.py | wc -l

Ah! I haven't thought of using wc, although I frequently use it to count the number of lines in my code. For awk, yes, I have to learn it. Thanks to you and the others who gave the example in bash.

Technically this will work on any shell not just bash but good luck! Shell scripting is rather fun once you get the hang of it. Though if I'm honest, if I get a shell script about 30+ lines I tend to back up and break out ruby/perl/python/anything but shell. Think of it as a succinct glue language and you'll do fine.

In the meantime feel free to use this python thing, its rather fun to be honest. Just wanted to demonstrate the unix-y way of doing it.

'wc -l' counts the number of lines. It also supports '-c' and '-b'.

To work with input split into columns, use awk. By default, it assumes the columns are separated with spaces. This can be customized with the '-F' option.

So your last example can be rewritten as

    awk -F, '{s+=$1} END{print s}' data.csv

For reference, you can do this using the wc core utility. The -l option makes it count the number of lines so 'wc -l' will do the same thing as your sum expression.

The first two can be done with wc:

  ls | wc -l
  ls | grep .py | wc -l

Add alias numfiles="echo $(ls -1 | wc -l)" to your ~/.bashrc

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.