py1line Chapter One
Yesterday I had a dream. About Python… I dreamed of some Python one-liners…
Many ppl have seen the awk1line and sed1line. And yet many ppl think Python is bloated, indent-hog. But I just want to prove that Python is not that bad at this aspect… Bloated but clear in thoughts! I'll follow awk1line as requirements and try Python one-liner implemention. I'm not very good at programming though so I'll do this progressively…
I'll put a one-page version in my wiki for others to edit, if exists…
Here It Comes
FILE SPACING:
# double space a file python -c 'import sys; print "\n".join(line for line in sys.stdin)'
# double space a file which already has blank lines in it. Output file # should contain no more than one blank line between lines of text. python -c 'import sys; print "\n".join(line for line in sys.stdin if not len(line) == 0 )'
# triple space a file python -c 'import sys; print "\n\n".join(line for line in sys.stdin)'
NUMBERING AND CALCULATIONS:
# precede each line by its line number FOR THAT FILE (left alignment). # Using a tab (\t) instead of space will preserve margins. python -c 'import sys; print "".join("%d\t%s"%(n + 1, line) for (n, line) in enumerate(sys.stdin))'
# precede each line by its line number FOR ALL FILES TOGETHER, with tab. python -c 'import sys,glob; map(lambda file: sys.stdout.write("".join("%d\t%s"%(n + 1, line) for(n, line) in enumerate(open(file)))), glob.glob("*"));'
# number each line of a file (number on left, right-aligned) # Double the percent signs if typing from the DOS command prompt. python -c 'import sys; print "".join("%5d %s"%(n + 1, line) for (n, line) in enumerate(sys.stdin))'
# number each line of file, but only print numbers if line is not blank # Remember caveats about Unix treatment of \r (mentioned above) python -c 'import sys; print "".join("%5d %s"%(n + 1, line) for (n, line) in enumerate(sys.stdin) if len(line)>0)'
# count lines (emulates "wc -l") python -c 'import sys; print sum(1 for line in sys.stdin)'
To be continued…

Discussion