Examples
The TAPL book contains 20 examples of One-liners (A Handful of Useful awk One-Liners) at the end of the book's first chapter.
Here are the very first of them:
- Print the total number of input lines: END { print NR }
- Print the tenth input line: NR == 10
- Print the last field of every input line: { print $NF }
Here are examples in J:
- A function avg to return the average of a list of numbers: avg=: +/ % #
- Quicksort: quicksort=: (($:@(<#[), (=#[), $:@(>#[)) ({~ ?@#)) ^: (1<#)
Here are examples in Perl:
- Look for duplicate words perl -0777 -ne 'print "$.: doubled $_\n" while /\b(\w+)\b\s+\b\1\b/gi'
- Find Palindromes in /usr/dict/words perl -lne 'print if $_ eq reverse' /usr/dict/words
- in-place edit of *.c files changing all foo to bar perl -p -i.bak -e 's/\bfoo\b/bar/g' *.c
Many one-liners are practical. For example, the following Perl one-liner will reverse all the bytes in a file:
perl -0777e 'print scalar reverse <>' filenameOne-liners are also used to show off the differential expressive power of programming languages. Frequently, one-liners are used to demonstrate programming ability. Contests are often held to see who can create the most exceptional one-liner.
The following example is a C program (a winning entry in the "Best one-liner" category of the IOCCC, here split to two lines for presentation).
main(int c,char**v){return!m(v,v);}m(char*s,char*t){return *t-42?*s?63==*t|*s==*t&&m(s+1,t+1):!*t:m(s,t+1)||*s&&m(s+1,t);}This one-liner program is a glob pattern matcher. It understands the glob characters `*' meaning `zero or more characters' and `?' meaning exactly one character, just like most Unix shells.
Run it with two args, the string and the glob pattern. The exit status is 0 (shell true) when the pattern matches, 1 otherwise. The glob pattern must match the whole string, so you may want to use * at the beginning and end of the pattern if you are looking for something in the middle. Examples:
$ prog foo 'f??'; echo $? $ prog 'best short program' '??st*o**p?*'; echo $?Read more about this topic: One-liner Program
Famous quotes containing the word examples:
“Histories are more full of examples of the fidelity of dogs than of friends.”
—Alexander Pope (16881744)
“No rules exist, and examples are simply life-savers answering the appeals of rules making vain attempts to exist.”
—André Breton (18961966)
“There are many examples of women that have excelled in learning, and even in war, but this is no reason we should bring em all up to Latin and Greek or else military discipline, instead of needle-work and housewifry.”
—Bernard Mandeville (16701733)