David Hancock

Jan 30

Saving a couple idioms

Things I’ve written down from articles lately, don’t want to lose them:

Nice awk example (count number of users of each shell):

awk -F: '{x[$7]+=1} END {for(z in x) {print z, x[z]}}' /etc/passwd

Nonobvious (to dumb me, at least) use of slicing in Python:

def reverse(str):
    return str[::-1]

print reverse('Bite me')

Using fileinput Python module:

import fileinput
for line in fileinput.input(): # cmd line files or stdin
    print fileinput.filelineno(), fileinput.filename(), line

for line in fileinput.input("test.txt", inplace=1):
    print fileinput.filelineno(), fileinput.filename(), line

Second example overwrites lines of test.txt with your munged lines.