Tugger the SLUGger!SLUG Mailing List Archives

Re: [SLUG] Tuesday afternoon shell command optimisation party!

Rick Welykochy wrote:
> Jamie Wilkinson wrote:
>> This one time, at band camp, Jeff Waugh wrote:
>>> Hi all,
>>> Here's a starting point. What's a more optimal way to perform this task? 
>>> :-)
>>>  sed 's#[^,]*##g' input.txt | tr -d '\n' | wc -m
>>> Tuesday afternoon shell optimisation party!
>> You want to count the total number of characters in a file, not including
>> newlines, that are on lines that don't start with a comma.
>> Does it have to be in shell? :-)
> How about this. You want to count the total number of commas in a file.
> python -c "import sys; print (''.join(sys.stdin.readlines())).count(',')" < 
> input.txt

You can simplify that slightly:

python -Sc "import sys; print sys.stdin.read().count(',')" < input.txt

This way is faster, too :)

If you want to avoid reading the whole file into memory:

python -Sc "import sys; print sum(l.count(',') for l in sys.stdin)" < input.txt