In
computer programming
Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as ana ...
, a one-liner program originally was textual input to the
command-line
A command-line interpreter or command-line processor uses a command-line interface (CLI) to receive commands from a user in the form of lines of text. This provides a means of setting parameters for the environment, invoking executables and pro ...
of an operating system
shell
Shell may refer to:
Architecture and design
* Shell (structure), a thin structure
** Concrete shell, a thin shell of concrete, usually with no interior columns or exterior buttresses
** Thin-shell structure
Science Biology
* Seashell, a hard o ...
that performed some function in just one line of input. In the present day, a one-liner can be
* an
expression
Expression may refer to:
Linguistics
* Expression (linguistics), a word, phrase, or sentence
* Fixed expression, a form of words with a specific meaning
* Idiom, a type of fixed expression
* Metaphorical expression, a particular word, phrase, o ...
written in the language of the shell;
* the invocation of an
interpreter together with program source for the interpreter to run;
* the invocation of a
compiler
In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs that ...
together with source to compile and instructions for
executing the compiled program.
Certain
dynamic languages for
scripting, such as
AWK
AWK (''awk'') is a domain-specific language designed for text processing and typically used as a data extraction and reporting tool. Like sed and grep, it is a filter, and is a standard feature of most Unix-like operating systems.
The AWK lang ...
,
sed
sed ("stream editor") is a Unix utility that parses and transforms text, using a simple, compact programming language. It was developed from 1973 to 1974 by Lee E. McMahon of Bell Labs,
and is available today for most operating systems.
sed w ...
, and
Perl
Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
, have traditionally been adept at expressing one-liners.
Shell interpreters such as
Unix shell
A Unix shell is a command-line Interpreter (computing), interpreter or shell (computing), shell that provides a command line user interface for Unix-like operating systems. The shell is both an interactive command language and a scripting langua ...
s or
Windows PowerShell
PowerShell is a task automation and configuration management program from Microsoft, consisting of a command-line shell and the associated scripting language. Initially a Windows component only, known as Windows PowerShell, it was made open-sourc ...
allow for the construction of powerful one-liners.
The use of the phrase ''one-liner'' has been widened to also include program-source for any language that does something useful in one line.
History
The concept of a one-liner program has been known since the 1960s with the release of the
APL programming language. With its terse syntax and powerful mathematical operators, APL allowed useful programs to be represented in a few symbols.
In the 1970s, one-liners became associated with the rise of the
home computer and
BASIC
BASIC (Beginners' All-purpose Symbolic Instruction Code) is a family of general-purpose, high-level programming languages designed for ease of use. The original version was created by John G. Kemeny and Thomas E. Kurtz at Dartmouth College ...
. Computer magazines published
type-in program
A type-in program or type-in listing was computer source code printed in a home computer magazine or book. It was meant to be entered via the keyboard by the reader and then saved to cassette tape or floppy disk. The result was a usable game, ...
s in many dialects of BASIC. Some magazines devoted regular columns solely to impressive short and one-line programs.
The word ''One-liner'' also has two references in the index of the book
The AWK Programming Language
''The AWK Programming Language'' is a well-known 1988 book written by Alfred V. Aho, Brian W. Kernighan, and Peter J. Weinberger and published by Addison-Wesley, often referred to as the gray book. The book describes the AWK programming language a ...
(the book is often referred to by the abbreviation ''TAPL''). It explains the programming language
AWK
AWK (''awk'') is a domain-specific language designed for text processing and typically used as a data extraction and reporting tool. Like sed and grep, it is a filter, and is a standard feature of most Unix-like operating systems.
The AWK lang ...
, which is part of the
Unix
Unix (; trademarked as UNIX) is a family of multitasking, multiuser computer operating systems that derive from the original AT&T Unix, whose development started in 1969 at the Bell Labs research center by Ken Thompson, Dennis Ritchie, and ot ...
operating system
An operating system (OS) is system software that manages computer hardware, software resources, and provides common services for computer programs.
Time-sharing operating systems schedule tasks for efficient use of the system and may also in ...
. The authors explain the birth of the ''one-liner'' paradigm with their daily work on early
Unix
Unix (; trademarked as UNIX) is a family of multitasking, multiuser computer operating systems that derive from the original AT&T Unix, whose development started in 1969 at the Bell Labs research center by Ken Thompson, Dennis Ritchie, and ot ...
machines:
Notice that this original definition of a ''one-liner'' implies immediate execution of the program without any compilation. So, in a strict sense, only source code for interpreted languages qualifies as a ''one-liner''. But this strict understanding of a ''one-liner'' was broadened in 1985 when the
IOCCC
The International Obfuscated C Code Contest (abbreviated IOCCC) is a computer programming contest for the most creatively obfuscated C code. Held annually, it is described as "celebrating 'ssyntactical opaqueness". The winning code for the 27t ...
introduced the category of ''Best One Liner'' for
C, which is a compiled language.
Examples
One-liners are also used to show off the differential expressive power of
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming ...
s. Frequently, one-liners are used to demonstrate programming ability. Contests are often held to see who can create the most exceptional one-liner.
BASIC
![10print](https://upload.wikimedia.org/wikipedia/commons/a/aa/10print.gif)
A single line of BASIC can typically hold up to 255 characters, and one liners ranged from simple games to graphical demos. One of the better-known demo one-liners is colloquially known as ''10PRINT'', written for the
Commodore 64
The Commodore 64, also known as the C64, is an 8-bit home computer introduced in January 1982 by Commodore International (first shown at the Consumer Electronics Show, January 7–10, 1982, in Las Vegas). It has been listed in the Guinness ...
:
10 PRINT CHR$(205.5+RND(1)); : GOTO 10
C
The following example is a
C program (a winning entry in the "Best one-liner" category of the
IOCCC
The International Obfuscated C Code Contest (abbreviated IOCCC) is a computer programming contest for the most creatively obfuscated C code. Held annually, it is described as "celebrating 'ssyntactical opaqueness". The winning code for the 27t ...
).
main(int c,char**v)m(char*s,char*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 shell
A Unix shell is a command-line Interpreter (computing), interpreter or shell (computing), shell that provides a command line user interface for Unix-like operating systems. The shell is both an interactive command language and a scripting langua ...
s.
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:
$ ./a.out foo 'f??'; echo $?
$ ./a.out 'best short program' '??st*o**p?*'; echo $?
AWK
The ''TAPL'' book contains 20 examples of ''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 (like
wc -l):
END
# Print the tenth input line:
NR 10
# Print the last field of every input line:
J
Here are examples in
J:
* A function avg to return the average of a list of numbers:
avg=: +/ % #
*
Quicksort
Quicksort is an efficient, general-purpose sorting algorithm. Quicksort was developed by British computer scientist Tony Hoare in 1959 and published in 1961, it is still a commonly used algorithm for sorting. Overall, it is slightly faster than ...
:
quicksort=: (($:@(<#[) , (=#[) , $:@(>#[)) ({~ ?@#)) ^: (1<#)
Perl
Here are examples in the
Perl
Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming ...
:
* 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
Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
one-liner will reverse all the bytes in a file:
perl -0777e 'print scalar reverse <>' filename
While most
Perl
Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
one-liners are imperative, Perl's support for anonymous functions, closures, map, filter (grep) and fold (List::Util::reduce) allows the creation of 'functional' one-liners.
This one-liner creates a function that can be used to return a list of primes up to the value of the first parameter:
my $z = sub { grep { $a=$_; !grep { !($a % $_) } (2..$_-1)} (2..$_[0]) }
It can be used on the command line, like this:
perl -e'
$,=",";print sub { grep { $a=$_; !grep { !($a % $_) } (2..$_-1)} (2..$_[0]) }->(shift)' number
to print out a comma-separated list of primes in the range 2 - number.
Haskell
The following
Haskell
Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lan ...
program is a one-liner: it sorts its input lines
ASCIIbetically.
main = (mapM_ putStrLn . Data.List.sort . lines) =<< getContents -- In ghci a qualified name like Data.List.sort will work, although as a standalone executable you'd need to import Data.List.
An even shorter version:
main = interact (unlines . Data.List.sort . lines) -- Ditto.
Usable on the command line like:
cat filename , ghc -e "interact (unlines . Data.List.sort . lines)"
Racket
The following
Racket program is equivalent to the above Haskell example:
#lang racket
(for-each displayln (sort (port->lines) string))
and this can be used on the command line as follows:
racket -e '
(for-each displayln (sort (port->lines) string))'
Python
Performing one-liners directly on the Unix command line can be accomplished by using
Python
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
's -cmd flag (-c for short), and typically requires the import of one or more modules. Statements are separated using ";" instead of newlines. For example, to print the last field of unix long listing:
ls -l , python -c "
import sys; ys.stdout.write('_'.join([line.split('_') ys.stdout.write('_'.join([line.split('_')[-1))_for_line_in_sys.stdin">ine.split('_')[-1.html"_;"title="ys.stdout.write('_'.join([line.split('_')[-1">ys.stdout.write('_'.join([line.split('_')[-1))_for_line_in_sys.stdin/syntaxhighlight>"
_Python_wrappers
Several_open-source_scripts_have_been_developed_to_facilitate_the_construction_of_Python_one-liners._Scripts_such_as
pyp
o
Pyline
import_commonly_used_modules_and_provide_more_human-readable_variables_in_an_attempt_to_make_Python_functionality_more_accessible_on_the_command_line._Here_is_a_redo_of_the_above_example_(printing_the_last_field_of_a_unix_long_listing):
ls_-l_.html" ;"title="1))_for_line_in_sys.stdin.html" ;"title="ine.split('_') ys.stdout.write('_'.join([line.split('_')[-1))_for_line_in_sys.stdin">ine.split('_')[-1.html"_;"title="ys.stdout.write('_'.join([line.split('_')[-1">ys.stdout.write('_'.join([line.split('_')[-1))_for_line_in_sys.stdin/syntaxhighlight>"
_Python_wrappers
Several_open-source_scripts_have_been_developed_to_facilitate_the_construction_of_Python_one-liners._Scripts_such_as
pyp
o
Pyline
import_commonly_used_modules_and_provide_more_human-readable_variables_in_an_attempt_to_make_Python_functionality_more_accessible_on_the_command_line._Here_is_a_redo_of_the_above_example_(printing_the_last_field_of_a_unix_long_listing):
ls_-l_">_pyp_"whitespace[-1_#_"whitespace"_represents_each_line_split_on_white_space_in_pyp
ls_-l_.html" ;"title="1.html" ;"title="ys.stdout.write(' '.join([line.split(' ')[-1">ys.stdout.write(' '.join([line.split(' ')[-1)) for line in sys.stdin">ine.split('_')[-1.html" ;"title="ys.stdout.write(' '.join([line.split(' ')[-1">ys.stdout.write(' '.join([line.split(' ')[-1)) for line in sys.stdin/syntaxhighlight>"
Python wrappers
Several open-source scripts have been developed to facilitate the construction of Python one-liners. Scripts such as
pyp
o
Pyline
import commonly used modules and provide more human-readable variables in an attempt to make Python functionality more accessible on the command line. Here is a redo of the above example (printing the last field of a unix long listing):
ls -l "> pyp "whitespace[-1 # "whitespace" represents each line split on white space in pyp
ls -l "> pyline "words[-1 # "words" represents each line split on white space in pyline
Executable libraries
The Python CGIHTTPServer module for example is also an executable library that performs as a web server with CGI. To start the web server enter:
$ python -m CGIHTTPServer
Serving HTTP on 0.0.0.0 port 8000 …
Tcl
Tcl
TCL or Tcl or TCLs may refer to:
Business
* TCL Technology, a Chinese consumer electronics and appliance company
**TCL Electronics, a subsidiary of TCL Technology
* Texas Collegiate League, a collegiate baseball league
* Trade Centre Limited ...
(Tool Command Language) is a dynamic programming/scripting language based on concepts of Lisp, C, and Unix shells. It can be used interactively, or by running scripts (programs) which can use a package system for structuring.[Following are direct quotes from that are available under the Creative Commons Attribution-ShareAlike License.]
Many strings are also well-formed lists. Every simple word is a list of length one, and elements of longer lists are separated by whitespace. For instance, a string that corresponds to a list of three elements:
set example {foo bar grill}
Strings with unbalanced quotes or braces, or non-space characters directly following closing braces, cannot be parsed as lists directly. You can explicitly split them to make a list.
The "constructor" for lists is of course called list. It's recommended to use when elements come from variable or command substitution (braces won't do that). As Tcl commands are lists anyway, the following is a full substitute for the list command:
proc list args {set args}
Windows PowerShell
Finding palindromes in file words.txt
Get-Content words.txt , Where { $_ -eq -join $_ $_.length-1)..0}
Piping semantics in PowerShell help enable complex scenarios with one-liner programs. This one-liner in PowerShell script takes a list of names and counts from a comma-separated value file, and returns the sum of the counts for each name.
ipcsv .\fruit.txt –H F, C, Group F, %{@{"$($_.Name)"=($_.Group, measure C -sum).Sum, sort value
See also
* Bookmarklet
A bookmarklet is a bookmark stored in a web browser that contains JavaScript commands that add new features to the browser. They are stored as the URL of a bookmark in a web browser or as a hyperlink on a web page. Bookmarklets are usually small ...
* Tcl
TCL or Tcl or TCLs may refer to:
Business
* TCL Technology, a Chinese consumer electronics and appliance company
**TCL Electronics, a subsidiary of TCL Technology
* Texas Collegiate League, a collegiate baseball league
* Trade Centre Limited ...
References
External links
{{Sister project links, commons=Perl (programming language), v=Topic:Perl, n=no, q=Perl, s=no, b=Perl Programming
* Perl Programming links
* Wikibooks
Wikibooks (previously called ''Wikimedia Free Textbook Project'' and ''Wikimedia-Textbooks'') is a wiki-based Wikimedia project hosted by the Wikimedia Foundation for the creation of free content digital textbooks and annotated texts that any ...
Free Tcl Programming introduction & download pdf
SourceForge
download website and also Multiple computer languages
Tcl Sources
main Tcl and Tk source code download website
Tcler's Wiki
Tcl/Tk scripts and reference clearing house
TkDocs
Tcl/Tk Official documentation and archives
Computer programming
Articles with example Haskell code
Articles with example C code
Articles with example Perl code
Articles with example Python (programming language) code
Articles with example Racket code