If you want to be really lazy—er, um, smart—let UNIX sort files for you. You can use sort to, for example, sort your address book alphabetically—as opposed to the random order you might have entered addresses in (see Code Listing 6.17).
To sort files with sort:
sort address.book > → sorted.address.book
Tip
If you have multiple files to sort, you can use sort file1 file2 file3 > complete.sorted.file, and the output will contain the contents of all three files, sorted, of course.
[ejr@hobbes manipulate]$ more address.book Schmidt, Sven, 1 Circle Drive, Denver, CO, 80221, 555-555-8382 Feldman, Fester, RR1, Billings, MT 62832, 285-555-0281 Brown, John, 1453 South Street, Tulsa, OK, 74114, 918-555-1234 Smith, Sally, 452 Center Ave., Salt Lake City, UT, 84000, 801-555-8982 Jones, Kelly, 14 Main Street, Santa Clara, CA, 95051, 408-555-7253 [ejr@hobbes manipulate]$ sort address.book Brown, John, 1453 South Street, Tulsa, OK, 74114, 918-555-1234 Feldman, Fester, RR1, Billings, MT 62832, 285-555-0281 Jones, Kelly, 14 Main Street, Santa Clara, CA, 95051, 408-555-7253 Schmidt, Sven, 1 Circle Drive, Denver, CO, 80221, 555-555-8382 Smith, Sally, 452 Center Ave., Salt Lake City, UT, 84000, 801-555-8982 [ejr@hobbes manipulate]$ sort address.book > sorted.address.book [ejr@hobbes manipulate]$ cat sorted.address.book Brown, John, 1453 South Street, Tulsa, OK, 74114, 918-555-1234 Feldman, Fester, RR1, Billings, MT 62832, 285-555-0281 Jones, Kelly, 14 Main Street, Santa Clara, CA, 95051, 408-555-7253 Schmidt, Sven, 1 Circle Drive, Denver, CO, 80221, 555-555-8382 Smith, Sally, 452 Center Ave., Salt Lake City, UT, 84000, 801-555-8982 [ejr@hobbes manipulate]$ |
Tip
You can sort fields in comma-delimited files by adding -t to the code. For example, sort -t, +1 address.book tells UNIX to sort by the second field. The -t and following character (,) indicate what character separates the fields—the comma in this case. If a character isn't given, sort thinks that white space marks the boundaries between fields. The +1 says to skip the first field and sort on the second one.
Tip
You can sort numerically too, with sort -n filename. If you don't use the -n flag, the output will be ordered based on the leftmost digits in the numbers—for example "1, 203, 50"—because the alphabetic sort starts at the left of the field.
18.218.168.16