First some context: This is the format of an /etc/passwd file (rough example)...

root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
rpc:x:32:32:Portmapper RPC user:/:/sbin/nologin
ntp:x:38:38::/etc/ntp:/sbin/nologin
haldaemon:x:68:68:HAL daemon:/:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin

Now then, can you sort that (numerically, descending) by UID (3rd field) and do it with less code? Show me how! I bet there's a way to optimize-out that split below...

cat /etc/passwd | perl -e 'print join ":", @$_ for sort { $b->[2] <=> +$a->[2] } map { [ split /:/, $_ ] } <>'

Granted, you can use the code below also, but it doesn't port to a certain flavor of Unix I have to work with more than I'd like... The Perl code works on all the platforms without changes...

cat /etc/passwd | sort -t : -k3 -nr # the above method works great with GNU /bin/sort!

Tommy
A mistake can be valuable or costly, depending on how faithfully you pursue correction

In reply to Golf: reverse sort /etc/passwd by UID by Tommy

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.