This page contains common examples of common awk-like operations (taken from Awk One-Liners Explained) not covered in Sed-Like Examples and Perl-Like Examples.
Find the line containing the largest (numeric) first field.
>>> print stream_vals('foo.csv', cols = 0) | enumerate()_ | filt(lambda (i, v): (v, i)) | (min_() | select_inds(1))
Note
The first two stages,
>>> stream_vals('foo.csv', cols = 0) | enumerate()_
enumerates the first fields of the lines.
The next stage,
filt(lambda (i, v): (v, i))
reverses the tuples. Using Python’s lexicographic ordering,
min_()
extracts the tuple with the smallest value. The enumeration is retrieved using
select_inds(1)
(note the use of sink chaining).
Print the last field of each line.
>>> print stream_vals('foo.csv') | select_inds(-1) | to_stream(sys.stdout)
Print the last field of the last line.
>>> print stream_vals('foo.csv') | select_inds(-1) | nth(-1)
Print the first two fields in reverse order on each line.
>>> print stream_vals('foo.csv') | select_inds((1, 0)) | to_stream(sys.stdout)
Swap first field with second on every line.
>>> print stream_vals('foo.csv') | \
... filt(lambda l: '%s,%s,%s' % (l[1], l[0], ','.join(l[2: ]))) | \
... to_stream(sys.stdout)
>>> print stream_vals('foo.csv') | \
... filt(lambda l: '%s,%s' % (l[0], ','.join(l[2: ]))) | \
... to_stream(sys.stdout)
>>> print stream_vals('foo.csv') | filt(lambda l: lle(reversed(l))) | to_stream(sys.stdout)