4 ms·
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 m
by S4M 12y ago
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)'
- chmielewski 12y agoAdd alias numfiles="echo $(ls -1 | wc -l)" to your ~/.bashrc
- foob 12y agoFor 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.
- alco 12y ago'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
- Denvercoder9 12y agoThe first two can be done with wc: ls | wc -l ls | grep .py | wc -l
- deleted 12y ago[deleted]
- mitchty 12y agoYou'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
- S4M 12y agoAh! 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.
- mitchty 12y agoTechnically 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.
- vram22 12y ago> 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
- Russell91 12y agoYea, 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.