Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: f70c7b785b
Fetching contributors…

Cannot retrieve contributors at this time

16302 lines (13199 sloc) 538.616 kb
\input texinfo
@c %**start of header
@setfilename coreutils.info
@settitle @sc{gnu} Coreutils
@c %**end of header
@include version.texi
@include constants.texi
@c Define new indices.
@defcodeindex op
@defcodeindex fl
@c Put everything in one index (arbitrarily chosen to be the concept index).
@syncodeindex fl cp
@syncodeindex fn cp
@syncodeindex ky cp
@syncodeindex op cp
@syncodeindex pg cp
@syncodeindex vr cp
@dircategory Basics
@direntry
* Coreutils: (coreutils). Core GNU (file, text, shell) utilities.
* Common options: (coreutils)Common options. Common options.
* File permissions: (coreutils)File permissions. Access modes.
* Date input formats: (coreutils)Date input formats.
@end direntry
@c FIXME: the following need documentation
@c * [: (coreutils)[ invocation. File/string tests.
@c * pinky: (coreutils)pinky invocation. FIXME.
@dircategory Individual utilities
@direntry
* arch: (coreutils)arch invocation. Print machine hardware name.
* base64: (coreutils)base64 invocation. Base64 encode/decode data.
* basename: (coreutils)basename invocation. Strip directory and suffix.
* cat: (coreutils)cat invocation. Concatenate and write files.
* chcon: (coreutils)chcon invocation. Change SELinux CTX of files.
* chgrp: (coreutils)chgrp invocation. Change file groups.
* chmod: (coreutils)chmod invocation. Change file permissions.
* chown: (coreutils)chown invocation. Change file owners/groups.
* chroot: (coreutils)chroot invocation. Specify the root directory.
* cksum: (coreutils)cksum invocation. Print POSIX CRC checksum.
* comm: (coreutils)comm invocation. Compare sorted files by line.
* cp: (coreutils)cp invocation. Copy files.
* csplit: (coreutils)csplit invocation. Split by context.
* cut: (coreutils)cut invocation. Print selected parts of lines.
* date: (coreutils)date invocation. Print/set system date and time.
* dd: (coreutils)dd invocation. Copy and convert a file.
* df: (coreutils)df invocation. Report file system disk usage.
* dir: (coreutils)dir invocation. List directories briefly.
* dircolors: (coreutils)dircolors invocation. Color setup for ls.
* dirname: (coreutils)dirname invocation. Strip last file name component.
* du: (coreutils)du invocation. Report on disk usage.
* echo: (coreutils)echo invocation. Print a line of text.
* env: (coreutils)env invocation. Modify the environment.
* expand: (coreutils)expand invocation. Convert tabs to spaces.
* expr: (coreutils)expr invocation. Evaluate expressions.
* factor: (coreutils)factor invocation. Print prime factors
* false: (coreutils)false invocation. Do nothing, unsuccessfully.
* fmt: (coreutils)fmt invocation. Reformat paragraph text.
* fold: (coreutils)fold invocation. Wrap long input lines.
* groups: (coreutils)groups invocation. Print group names a user is in.
* head: (coreutils)head invocation. Output the first part of files.
* hostid: (coreutils)hostid invocation. Print numeric host identifier.
* hostname: (coreutils)hostname invocation. Print or set system name.
* id: (coreutils)id invocation. Print user identity.
* install: (coreutils)install invocation. Copy and change attributes.
* join: (coreutils)join invocation. Join lines on a common field.
* kill: (coreutils)kill invocation. Send a signal to processes.
* link: (coreutils)link invocation. Make hard links between files.
* ln: (coreutils)ln invocation. Make links between files.
* logname: (coreutils)logname invocation. Print current login name.
* ls: (coreutils)ls invocation. List directory contents.
* md5sum: (coreutils)md5sum invocation. Print or check MD5 digests.
* mkdir: (coreutils)mkdir invocation. Create directories.
* mkfifo: (coreutils)mkfifo invocation. Create FIFOs (named pipes).
* mknod: (coreutils)mknod invocation. Create special files.
* mktemp: (coreutils)mktemp invocation. Create temporary files.
* mv: (coreutils)mv invocation. Rename files.
* nice: (coreutils)nice invocation. Modify niceness.
* nl: (coreutils)nl invocation. Number lines and write files.
* nohup: (coreutils)nohup invocation. Immunize to hangups.
* nproc: (coreutils)nproc invocation. Print the number of processors.
* od: (coreutils)od invocation. Dump files in octal, etc.
* paste: (coreutils)paste invocation. Merge lines of files.
* pathchk: (coreutils)pathchk invocation. Check file name portability.
* pr: (coreutils)pr invocation. Paginate or columnate files.
* printenv: (coreutils)printenv invocation. Print environment variables.
* printf: (coreutils)printf invocation. Format and print data.
* ptx: (coreutils)ptx invocation. Produce permuted indexes.
* pwd: (coreutils)pwd invocation. Print working directory.
* readlink: (coreutils)readlink invocation. Print referent of a symlink.
* rm: (coreutils)rm invocation. Remove files.
* rmdir: (coreutils)rmdir invocation. Remove empty directories.
* runcon: (coreutils)runcon invocation. Run in specified SELinux CTX.
* seq: (coreutils)seq invocation. Print numeric sequences
* sha1sum: (coreutils)sha1sum invocation. Print or check SHA-1 digests.
* sha2: (coreutils)sha2 utilities. Print or check SHA-2 digests.
* shred: (coreutils)shred invocation. Remove files more securely.
* shuf: (coreutils)shuf invocation. Shuffling text files.
* sleep: (coreutils)sleep invocation. Delay for a specified time.
* sort: (coreutils)sort invocation. Sort text files.
* split: (coreutils)split invocation. Split into fixed-size pieces.
* stat: (coreutils)stat invocation. Report file(system) status.
* stdbuf: (coreutils)stdbuf invocation. Modify stdio buffering.
* stty: (coreutils)stty invocation. Print/change terminal settings.
* su: (coreutils)su invocation. Modify user and group ID.
* sum: (coreutils)sum invocation. Print traditional checksum.
* sync: (coreutils)sync invocation. Synchronize memory and disk.
* tac: (coreutils)tac invocation. Reverse files.
* tail: (coreutils)tail invocation. Output the last part of files.
* tee: (coreutils)tee invocation. Redirect to multiple files.
* test: (coreutils)test invocation. File/string tests.
* timeout: (coreutils)timeout invocation. Run with time limit.
* touch: (coreutils)touch invocation. Change file timestamps.
* tr: (coreutils)tr invocation. Translate characters.
* true: (coreutils)true invocation. Do nothing, successfully.
* truncate: (coreutils)truncate invocation. Shrink/extend size of a file.
* tsort: (coreutils)tsort invocation. Topological sort.
* tty: (coreutils)tty invocation. Print terminal name.
* uname: (coreutils)uname invocation. Print system information.
* unexpand: (coreutils)unexpand invocation. Convert spaces to tabs.
* uniq: (coreutils)uniq invocation. Uniquify files.
* unlink: (coreutils)unlink invocation. Removal via unlink(2).
* uptime: (coreutils)uptime invocation. Print uptime and load.
* users: (coreutils)users invocation. Print current user names.
* vdir: (coreutils)vdir invocation. List directories verbosely.
* wc: (coreutils)wc invocation. Line, word, and byte counts.
* who: (coreutils)who invocation. Print who is logged in.
* whoami: (coreutils)whoami invocation. Print effective user ID.
* yes: (coreutils)yes invocation. Print a string indefinitely.
@end direntry
@copying
This manual documents version @value{VERSION} of the @sc{gnu} core
utilities, including the standard programs for text and file manipulation.
Copyright @copyright{} 1994-1996, 2000-2010 Free Software Foundation, Inc.
@quotation
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts. A copy of the license is included in the section entitled ``GNU
Free Documentation License''.
@end quotation
@end copying
@titlepage
@title @sc{gnu} @code{Coreutils}
@subtitle Core GNU utilities
@subtitle for version @value{VERSION}, @value{UPDATED}
@author David MacKenzie et al.
@page
@vskip 0pt plus 1filll
@insertcopying
@end titlepage
@shortcontents
@contents
@ifnottex
@node Top
@top GNU Coreutils
@insertcopying
@end ifnottex
@cindex core utilities
@cindex text utilities
@cindex shell utilities
@cindex file utilities
@menu
* Introduction:: Caveats, overview, and authors
* Common options:: Common options
* Output of entire files:: cat tac nl od base64
* Formatting file contents:: fmt pr fold
* Output of parts of files:: head tail split csplit
* Summarizing files:: wc sum cksum md5sum sha1sum sha2
* Operating on sorted files:: sort shuf uniq comm ptx tsort
* Operating on fields:: cut paste join
* Operating on characters:: tr expand unexpand
* Directory listing:: ls dir vdir dircolors
* Basic operations:: cp dd install mv rm shred
* Special file types:: mkdir rmdir unlink mkfifo mknod ln link readlink
* Changing file attributes:: chgrp chmod chown touch
* Disk usage:: df du stat sync truncate
* Printing text:: echo printf yes
* Conditions:: false true test expr
* Redirection:: tee
* File name manipulation:: dirname basename pathchk mktemp
* Working context:: pwd stty printenv tty
* User information:: id logname whoami groups users who
* System context:: date arch nproc uname hostname hostid uptime
* SELinux context:: chcon runcon
* Modified command invocation:: chroot env nice nohup stdbuf su timeout
* Process control:: kill
* Delaying:: sleep
* Numeric operations:: factor seq
* File permissions:: Access modes
* Date input formats:: Specifying date strings
* Opening the software toolbox:: The software tools philosophy
* GNU Free Documentation License:: Copying and sharing this manual
* Concept index:: General index
@detailmenu
--- The Detailed Node Listing ---
Common Options
* Exit status:: Indicating program success or failure
* Backup options:: Backup options
* Block size:: Block size
* Signal specifications:: Specifying signals
* Disambiguating names and IDs:: chgrp and chown owner and group syntax
* Random sources:: Sources of random data
* Target directory:: Target directory
* Trailing slashes:: Trailing slashes
* Traversing symlinks:: Traversing symlinks to directories
* Treating / specially:: Treating / specially
* Standards conformance:: Standards conformance
Output of entire files
* cat invocation:: Concatenate and write files
* tac invocation:: Concatenate and write files in reverse
* nl invocation:: Number lines and write files
* od invocation:: Write files in octal or other formats
* base64 invocation:: Transform data into printable data
Formatting file contents
* fmt invocation:: Reformat paragraph text
* pr invocation:: Paginate or columnate files for printing
* fold invocation:: Wrap input lines to fit in specified width
Output of parts of files
* head invocation:: Output the first part of files
* tail invocation:: Output the last part of files
* split invocation:: Split a file into fixed-size pieces
* csplit invocation:: Split a file into context-determined pieces
Summarizing files
* wc invocation:: Print newline, word, and byte counts
* sum invocation:: Print checksum and block counts
* cksum invocation:: Print CRC checksum and byte counts
* md5sum invocation:: Print or check MD5 digests
* sha1sum invocation:: Print or check SHA-1 digests
* sha2 utilities:: Print or check SHA-2 digests
Operating on sorted files
* sort invocation:: Sort text files
* shuf invocation:: Shuffle text files
* uniq invocation:: Uniquify files
* comm invocation:: Compare two sorted files line by line
* ptx invocation:: Produce a permuted index of file contents
* tsort invocation:: Topological sort
@command{ptx}: Produce permuted indexes
* General options in ptx:: Options which affect general program behavior
* Charset selection in ptx:: Underlying character set considerations
* Input processing in ptx:: Input fields, contexts, and keyword selection
* Output formatting in ptx:: Types of output format, and sizing the fields
* Compatibility in ptx:: The @acronym{GNU} extensions to @command{ptx}
Operating on fields
* cut invocation:: Print selected parts of lines
* paste invocation:: Merge lines of files
* join invocation:: Join lines on a common field
Operating on characters
* tr invocation:: Translate, squeeze, and/or delete characters
* expand invocation:: Convert tabs to spaces
* unexpand invocation:: Convert spaces to tabs
@command{tr}: Translate, squeeze, and/or delete characters
* Character sets:: Specifying sets of characters
* Translating:: Changing one set of characters to another
* Squeezing:: Squeezing repeats and deleting
Directory listing
* ls invocation:: List directory contents
* dir invocation:: Briefly list directory contents
* vdir invocation:: Verbosely list directory contents
* dircolors invocation:: Color setup for @command{ls}
@command{ls}: List directory contents
* Which files are listed:: Which files are listed
* What information is listed:: What information is listed
* Sorting the output:: Sorting the output
* Details about version sort:: More details about version sort
* General output formatting:: General output formatting
* Formatting the file names:: Formatting the file names
Basic operations
* cp invocation:: Copy files and directories
* dd invocation:: Convert and copy a file
* install invocation:: Copy files and set attributes
* mv invocation:: Move (rename) files
* rm invocation:: Remove files or directories
* shred invocation:: Remove files more securely
Special file types
* link invocation:: Make a hard link via the link syscall
* ln invocation:: Make links between files
* mkdir invocation:: Make directories
* mkfifo invocation:: Make FIFOs (named pipes)
* mknod invocation:: Make block or character special files
* readlink invocation:: Print value of a symlink or canonical file name
* rmdir invocation:: Remove empty directories
* unlink invocation:: Remove files via unlink syscall
Changing file attributes
* chown invocation:: Change file owner and group
* chgrp invocation:: Change group ownership
* chmod invocation:: Change access permissions
* touch invocation:: Change file timestamps
Disk usage
* df invocation:: Report file system disk space usage
* du invocation:: Estimate file space usage
* stat invocation:: Report file or file system status
* sync invocation:: Synchronize data on disk with memory
* truncate invocation:: Shrink or extend the size of a file
Printing text
* echo invocation:: Print a line of text
* printf invocation:: Format and print data
* yes invocation:: Print a string until interrupted
Conditions
* false invocation:: Do nothing, unsuccessfully
* true invocation:: Do nothing, successfully
* test invocation:: Check file types and compare values
* expr invocation:: Evaluate expressions
@command{test}: Check file types and compare values
* File type tests:: File type tests
* Access permission tests:: Access permission tests
* File characteristic tests:: File characteristic tests
* String tests:: String tests
* Numeric tests:: Numeric tests
@command{expr}: Evaluate expression
* String expressions:: + : match substr index length
* Numeric expressions:: + - * / %
* Relations for expr:: | & < <= = == != >= >
* Examples of expr:: Examples of using @command{expr}
Redirection
* tee invocation:: Redirect output to multiple files or processes
File name manipulation
* basename invocation:: Strip directory and suffix from a file name
* dirname invocation:: Strip last file name component
* pathchk invocation:: Check file name validity and portability
* mktemp invocation:: Create temporary file or directory
Working context
* pwd invocation:: Print working directory
* stty invocation:: Print or change terminal characteristics
* printenv invocation:: Print all or some environment variables
* tty invocation:: Print file name of terminal on standard input
@command{stty}: Print or change terminal characteristics
* Control:: Control settings
* Input:: Input settings
* Output:: Output settings
* Local:: Local settings
* Combination:: Combination settings
* Characters:: Special characters
* Special:: Special settings
User information
* id invocation:: Print user identity
* logname invocation:: Print current login name
* whoami invocation:: Print effective user ID
* groups invocation:: Print group names a user is in
* users invocation:: Print login names of users currently logged in
* who invocation:: Print who is currently logged in
System context
* arch invocation:: Print machine hardware name
* date invocation:: Print or set system date and time
* nproc invocation:: Print the number of processors
* uname invocation:: Print system information
* hostname invocation:: Print or set system name
* hostid invocation:: Print numeric host identifier
* uptime invocation:: Print system uptime and load
@command{date}: Print or set system date and time
* Time conversion specifiers:: %[HIklMNpPrRsSTXzZ]
* Date conversion specifiers:: %[aAbBcCdDeFgGhjmuUVwWxyY]
* Literal conversion specifiers:: %[%nt]
* Padding and other flags:: Pad with zeros, spaces, etc.
* Setting the time:: Changing the system clock
* Options for date:: Instead of the current time
* Date input formats:: Specifying date strings
* Examples of date:: Examples
SELinux context
* chcon invocation:: Change SELinux context of file
* runcon invocation:: Run a command in specified SELinux context
Modified command invocation
* chroot invocation:: Run a command with a different root directory
* env invocation:: Run a command in a modified environment
* nice invocation:: Run a command with modified niceness
* nohup invocation:: Run a command immune to hangups
* stdbuf invocation:: Run a command with modified I/O buffering
* su invocation:: Run a command with substitute user and group ID
* timeout invocation:: Run a command with a time limit
Process control
* kill invocation:: Sending a signal to processes.
Delaying
* sleep invocation:: Delay for a specified time
Numeric operations
* factor invocation:: Print prime factors
* seq invocation:: Print numeric sequences
File permissions
* Mode Structure:: Structure of file mode bits
* Symbolic Modes:: Mnemonic representation of file mode bits
* Numeric Modes:: File mode bits as octal numbers
* Directory Setuid and Setgid:: Set-user-ID and set-group-ID on directories
Date input formats
* General date syntax:: Common rules
* Calendar date items:: 19 Dec 1994
* Time of day items:: 9:20pm
* Time zone items:: @sc{est}, @sc{pdt}, @sc{gmt}
* Day of week items:: Monday and others
* Relative items in date strings:: next tuesday, 2 years ago
* Pure numbers in date strings:: 19931219, 1440
* Seconds since the Epoch:: @@1078100502
* Specifying time zone rules:: TZ="America/New_York", TZ="UTC0"
* Authors of parse_datetime:: Bellovin, Eggert, Salz, Berets, et al
Opening the software toolbox
* Toolbox introduction:: Toolbox introduction
* I/O redirection:: I/O redirection
* The who command:: The @command{who} command
* The cut command:: The @command{cut} command
* The sort command:: The @command{sort} command
* The uniq command:: The @command{uniq} command
* Putting the tools together:: Putting the tools together
Copying This Manual
* GNU Free Documentation License:: Copying and sharing this manual
@end detailmenu
@end menu
@node Introduction
@chapter Introduction
This manual is a work in progress: many sections make no attempt to explain
basic concepts in a way suitable for novices. Thus, if you are interested,
please get involved in improving this manual. The entire @sc{gnu} community
will benefit.
@cindex @acronym{POSIX}
The @sc{gnu} utilities documented here are mostly compatible with the
@acronym{POSIX} standard.
@cindex bugs, reporting
Please report bugs to @email{bug-coreutils@@gnu.org}. Remember
to include the version number, machine architecture, input files, and
any other information needed to reproduce the bug: your input, what you
expected, what you got, and why it is wrong. Diffs are welcome, but
please include a description of the problem as well, since this is
sometimes difficult to infer. @xref{Bugs, , , gcc, Using and Porting GNU CC}.
@cindex Berry, K.
@cindex Paterson, R.
@cindex Stallman, R.
@cindex Pinard, F.
@cindex MacKenzie, D.
@cindex Meyering, J.
@cindex Youmans, B.
This manual was originally derived from the Unix man pages in the
distributions, which were written by David MacKenzie and updated by Jim
Meyering. What you are reading now is the authoritative documentation
for these utilities; the man pages are no longer being maintained. The
original @command{fmt} man page was written by Ross Paterson. Fran@,{c}ois
Pinard did the initial conversion to Texinfo format. Karl Berry did the
indexing, some reorganization, and editing of the results. Brian
Youmans of the Free Software Foundation office staff combined the
manuals for textutils, fileutils, and sh-utils to produce the present
omnibus manual. Richard Stallman contributed his usual invaluable
insights to the overall process.
@node Common options
@chapter Common options
@macro optBackup
@item -b
@itemx @w{@kbd{--backup}[=@var{method}]}
@opindex -b
@opindex --backup
@vindex VERSION_CONTROL
@cindex backups, making
@xref{Backup options}.
Make a backup of each file that would otherwise be overwritten or removed.
@end macro
@macro optBackupSuffix
@item -S @var{suffix}
@itemx --suffix=@var{suffix}
@opindex -S
@opindex --suffix
Append @var{suffix} to each backup file made with @option{-b}.
@xref{Backup options}.
@end macro
@macro optTargetDirectory
@item -t @var{directory}
@itemx @w{@kbd{--target-directory}=@var{directory}}
@opindex -t
@opindex --target-directory
@cindex target directory
@cindex destination directory
Specify the destination @var{directory}.
@xref{Target directory}.
@end macro
@macro optNoTargetDirectory
@item -T
@itemx --no-target-directory
@opindex -T
@opindex --no-target-directory
@cindex target directory
@cindex destination directory
Do not treat the last operand specially when it is a directory or a
symbolic link to a directory. @xref{Target directory}.
@end macro
@macro optNull{cmd}
@item -0
@opindex -0
@itemx --null
@opindex --null
@cindex output @sc{nul}-byte-terminated lines
Output a zero byte (@acronym{ASCII} @sc{nul}) at the end of each line,
rather than a newline. This option enables other programs to parse the
output of @command{\cmd\} even when that output would contain data
with embedded newlines.
@end macro
@macro optSi
@itemx --si
@opindex --si
@cindex SI output
Append an SI-style abbreviation to each size, such as @samp{M} for
megabytes. Powers of 1000 are used, not 1024; @samp{M} stands for
1,000,000 bytes. This option is equivalent to
@option{--block-size=si}. Use the @option{-h} or
@option{--human-readable} option if
you prefer powers of 1024.
@end macro
@macro optHumanReadable
@item -h
@itemx --human-readable
@opindex -h
@opindex --human-readable
@cindex human-readable output
Append a size letter to each size, such as @samp{M} for mebibytes.
Powers of 1024 are used, not 1000; @samp{M} stands for 1,048,576 bytes.
This option is equivalent to @option{--block-size=human-readable}.
Use the @option{--si} option if you prefer powers of 1000.
@end macro
@macro optStripTrailingSlashes
@itemx @w{@kbd{--strip-trailing-slashes}}
@opindex --strip-trailing-slashes
@cindex stripping trailing slashes
Remove any trailing slashes from each @var{source} argument.
@xref{Trailing slashes}.
@end macro
@macro mayConflictWithShellBuiltIn{cmd}
@cindex conflicts with shell built-ins
@cindex built-in shell commands, conflicts with
Due to shell aliases and built-in @command{\cmd\} command, using an
unadorned @command{\cmd\} interactively or in a script may get you
different functionality than that described here. Invoke it via
@command{env} (i.e., @code{env \cmd\ @dots{}}) to avoid interference
from the shell.
@end macro
@macro multiplierSuffixes{varName}
@var{\varName\} may be, or may be an integer optionally followed by,
one of the following multiplicative suffixes:
@example
@samp{b} => 512 ("blocks")
@samp{KB} => 1000 (KiloBytes)
@samp{K} => 1024 (KibiBytes)
@samp{MB} => 1000*1000 (MegaBytes)
@samp{M} => 1024*1024 (MebiBytes)
@samp{GB} => 1000*1000*1000 (GigaBytes)
@samp{G} => 1024*1024*1024 (GibiBytes)
@end example
and so on for @samp{T}, @samp{P}, @samp{E}, @samp{Z}, and @samp{Y}.
@end macro
@c FIXME: same as above, but no ``blocks'' line.
@macro multiplierSuffixesNoBlocks{varName}
@var{\varName\} may be, or may be an integer optionally followed by,
one of the following multiplicative suffixes:
@example
@samp{KB} => 1000 (KiloBytes)
@samp{K} => 1024 (KibiBytes)
@samp{MB} => 1000*1000 (MegaBytes)
@samp{M} => 1024*1024 (MebiBytes)
@samp{GB} => 1000*1000*1000 (GigaBytes)
@samp{G} => 1024*1024*1024 (GibiBytes)
@end example
and so on for @samp{T}, @samp{P}, @samp{E}, @samp{Z}, and @samp{Y}.
@end macro
@cindex common options
Certain options are available in all of these programs. Rather than
writing identical descriptions for each of the programs, they are
described here. (In fact, every @sc{gnu} program accepts (or should accept)
these options.)
@vindex POSIXLY_CORRECT
Normally options and operands can appear in any order, and programs act
as if all the options appear before any operands. For example,
@samp{sort -r passwd -t :} acts like @samp{sort -r -t : passwd}, since
@samp{:} is an option-argument of @option{-t}. However, if the
@env{POSIXLY_CORRECT} environment variable is set, options must appear
before operands, unless otherwise specified for a particular command.
A few programs can usefully have trailing operands with leading
@samp{-}. With such a program, options must precede operands even if
@env{POSIXLY_CORRECT} is not set, and this fact is noted in the
program description. For example, the @command{env} command's options
must appear before its operands, since in some cases the operands
specify a command that itself contains options.
Most programs that accept long options recognize unambiguous
abbreviations of those options. For example, @samp{rmdir
--ignore-fail-on-non-empty} can be invoked as @samp{rmdir
--ignore-fail} or even @samp{rmdir --i}. Ambiguous options, such as
@samp{ls --h}, are identified as such.
Some of these programs recognize the @option{--help} and @option{--version}
options only when one of them is the sole command line argument. For
these programs, abbreviations of the long options are not always recognized.
@table @samp
@item --help
@opindex --help
@cindex help, online
Print a usage message listing all available options, then exit successfully.
@item --version
@opindex --version
@cindex version number, finding
Print the version number, then exit successfully.
@item --
@opindex --
@cindex option delimiter
Delimit the option list. Later arguments, if any, are treated as
operands even if they begin with @samp{-}. For example, @samp{sort --
-r} reads from the file named @file{-r}.
@end table
@cindex standard input
@cindex standard output
A single @samp{-} operand is not really an option, though it looks like one. It
stands for standard input, or for standard output if that is clear from
the context. For example, @samp{sort -} reads from standard input,
and is equivalent to plain @samp{sort}, and @samp{tee -} writes an
extra copy of its input to standard output. Unless otherwise
specified, @samp{-} can appear as any operand that requires a file
name.
@menu
* Exit status:: Indicating program success or failure.
* Backup options:: -b -S, in some programs.
* Block size:: BLOCK_SIZE and --block-size, in some programs.
* Signal specifications:: Specifying signals using the --signal option.
* Disambiguating names and IDs:: chgrp and chown owner and group syntax
* Random sources:: --random-source, in some programs.
* Target directory:: Specifying a target directory, in some programs.
* Trailing slashes:: --strip-trailing-slashes, in some programs.
* Traversing symlinks:: -H, -L, or -P, in some programs.
* Treating / specially:: --preserve-root and --no-preserve-root.
* Special built-in utilities:: @command{break}, @command{:}, @command{eval}, @dots{}
* Standards conformance:: Conformance to the @acronym{POSIX} standard.
@end menu
@node Exit status
@section Exit status
@macro exitstatus
An exit status of zero indicates success,
and a nonzero value indicates failure.
@end macro
Nearly every command invocation yields an integral @dfn{exit status}
that can be used to change how other commands work.
For the vast majority of commands, an exit status of zero indicates
success. Failure is indicated by a nonzero value---typically
@samp{1}, though it may differ on unusual platforms as @acronym{POSIX}
requires only that it be nonzero.
However, some of the programs documented here do produce
other exit status values and a few associate different
meanings with the values @samp{0} and @samp{1}.
Here are some of the exceptions:
@command{chroot}, @command{env}, @command{expr}, @command{nice},
@command{nohup}, @command{printenv}, @command{sort}, @command{stdbuf},
@command{su}, @command{test}, @command{timeout}, @command{tty}.
@node Backup options
@section Backup options
@cindex backup options
Some @sc{gnu} programs (at least @command{cp}, @command{install},
@command{ln}, and @command{mv}) optionally make backups of files
before writing new versions.
These options control the details of these backups. The options are also
briefly mentioned in the descriptions of the particular programs.
@table @samp
@item -b
@itemx @w{@kbd{--backup}[=@var{method}]}
@opindex -b
@opindex --backup
@vindex VERSION_CONTROL
@cindex backups, making
Make a backup of each file that would otherwise be overwritten or removed.
Without this option, the original versions are destroyed.
Use @var{method} to determine the type of backups to make.
When this option is used but @var{method} is not specified,
then the value of the @env{VERSION_CONTROL}
environment variable is used. And if @env{VERSION_CONTROL} is not set,
the default backup type is @samp{existing}.
Note that the short form of this option, @option{-b} does not accept any
argument. Using @option{-b} is equivalent to using @option{--backup=existing}.
@vindex version-control @r{Emacs variable}
This option corresponds to the Emacs variable @samp{version-control};
the values for @var{method} are the same as those used in Emacs.
This option also accepts more descriptive names.
The valid @var{method}s are (unique abbreviations are accepted):
@table @samp
@item none
@itemx off
@opindex none @r{backup method}
Never make backups.
@item numbered
@itemx t
@opindex numbered @r{backup method}
Always make numbered backups.
@item existing
@itemx nil
@opindex existing @r{backup method}
Make numbered backups of files that already have them, simple backups
of the others.
@item simple
@itemx never
@opindex simple @r{backup method}
Always make simple backups. Please note @samp{never} is not to be
confused with @samp{none}.
@end table
@item -S @var{suffix}
@itemx --suffix=@var{suffix}
@opindex -S
@opindex --suffix
@cindex backup suffix
@vindex SIMPLE_BACKUP_SUFFIX
Append @var{suffix} to each backup file made with @option{-b}. If this
option is not specified, the value of the @env{SIMPLE_BACKUP_SUFFIX}
environment variable is used. And if @env{SIMPLE_BACKUP_SUFFIX} is not
set, the default is @samp{~}, just as in Emacs.
@end table
@node Block size
@section Block size
@cindex block size
Some @sc{gnu} programs (at least @command{df}, @command{du}, and
@command{ls}) display sizes in ``blocks''. You can adjust the block size
and method of display to make sizes easier to read. The block size
used for display is independent of any file system block size.
Fractional block counts are rounded up to the nearest integer.
@opindex --block-size=@var{size}
@vindex BLOCKSIZE
@vindex BLOCK_SIZE
@vindex DF_BLOCK_SIZE
@vindex DU_BLOCK_SIZE
@vindex LS_BLOCK_SIZE
@vindex POSIXLY_CORRECT@r{, and block size}
The default block size is chosen by examining the following environment
variables in turn; the first one that is set determines the block size.
@table @code
@item DF_BLOCK_SIZE
This specifies the default block size for the @command{df} command.
Similarly, @env{DU_BLOCK_SIZE} specifies the default for @command{du} and
@env{LS_BLOCK_SIZE} for @command{ls}.
@item BLOCK_SIZE
This specifies the default block size for all three commands, if the
above command-specific environment variables are not set.
@item BLOCKSIZE
This specifies the default block size for all values that are normally
printed as blocks, if neither @env{BLOCK_SIZE} nor the above
command-specific environment variables are set. Unlike the other
environment variables, @env{BLOCKSIZE} does not affect values that are
normally printed as byte counts, e.g., the file sizes contained in
@code{ls -l} output.
@item POSIXLY_CORRECT
If neither @env{@var{command}_BLOCK_SIZE}, nor @env{BLOCK_SIZE}, nor
@env{BLOCKSIZE} is set, but this variable is set, the block size
defaults to 512.
@end table
If none of the above environment variables are set, the block size
currently defaults to 1024 bytes in most contexts, but this number may
change in the future. For @command{ls} file sizes, the block size
defaults to 1 byte.
@cindex human-readable output
@cindex SI output
A block size specification can be a positive integer specifying the number
of bytes per block, or it can be @code{human-readable} or @code{si} to
select a human-readable format. Integers may be followed by suffixes
that are upward compatible with the
@uref{http://www.bipm.fr/enus/3_SI/si-prefixes.html, SI prefixes}
for decimal multiples and with the
@uref{http://physics.nist.gov/cuu/Units/binary.html, IEC 60027-2
prefixes for binary multiples}.
With human-readable formats, output sizes are followed by a size letter
such as @samp{M} for megabytes. @code{BLOCK_SIZE=human-readable} uses
powers of 1024; @samp{M} stands for 1,048,576 bytes.
@code{BLOCK_SIZE=si} is similar, but uses powers of 1000 and appends
@samp{B}; @samp{MB} stands for 1,000,000 bytes.
@vindex LC_NUMERIC
A block size specification preceded by @samp{'} causes output sizes to
be displayed with thousands separators. The @env{LC_NUMERIC} locale
specifies the thousands separator and grouping. For example, in an
American English locale, @samp{--block-size="'1kB"} would cause a size
of 1234000 bytes to be displayed as @samp{1,234}. In the default C
locale, there is no thousands separator so a leading @samp{'} has no
effect.
An integer block size can be followed by a suffix to specify a
multiple of that size. A bare size letter,
or one followed by @samp{iB}, specifies
a multiple using powers of 1024. A size letter followed by @samp{B}
specifies powers of 1000 instead. For example, @samp{1M} and
@samp{1MiB} are equivalent to @samp{1048576}, whereas @samp{1MB} is
equivalent to @samp{1000000}.
A plain suffix without a preceding integer acts as if @samp{1} were
prepended, except that it causes a size indication to be appended to
the output. For example, @samp{--block-size="kB"} displays 3000 as
@samp{3kB}.
The following suffixes are defined. Large sizes like @code{1Y}
may be rejected by your computer due to limitations of its arithmetic.
@table @samp
@item kB
@cindex kilobyte, definition of
kilobyte: @math{10^3 = 1000}.
@item k
@itemx K
@itemx KiB
@cindex kibibyte, definition of
kibibyte: @math{2^{10} = 1024}. @samp{K} is special: the SI prefix is
@samp{k} and the IEC 60027-2 prefix is @samp{Ki}, but tradition and
@acronym{POSIX} use @samp{k} to mean @samp{KiB}.
@item MB
@cindex megabyte, definition of
megabyte: @math{10^6 = 1,000,000}.
@item M
@itemx MiB
@cindex mebibyte, definition of
mebibyte: @math{2^{20} = 1,048,576}.
@item GB
@cindex gigabyte, definition of
gigabyte: @math{10^9 = 1,000,000,000}.
@item G
@itemx GiB
@cindex gibibyte, definition of
gibibyte: @math{2^{30} = 1,073,741,824}.
@item TB
@cindex terabyte, definition of
terabyte: @math{10^{12} = 1,000,000,000,000}.
@item T
@itemx TiB
@cindex tebibyte, definition of
tebibyte: @math{2^{40} = 1,099,511,627,776}.
@item PB
@cindex petabyte, definition of
petabyte: @math{10^{15} = 1,000,000,000,000,000}.
@item P
@itemx PiB
@cindex pebibyte, definition of
pebibyte: @math{2^{50} = 1,125,899,906,842,624}.
@item EB
@cindex exabyte, definition of
exabyte: @math{10^{18} = 1,000,000,000,000,000,000}.
@item E
@itemx EiB
@cindex exbibyte, definition of
exbibyte: @math{2^{60} = 1,152,921,504,606,846,976}.
@item ZB
@cindex zettabyte, definition of
zettabyte: @math{10^{21} = 1,000,000,000,000,000,000,000}
@item Z
@itemx ZiB
@math{2^{70} = 1,180,591,620,717,411,303,424}.
(@samp{Zi} is a @acronym{GNU} extension to IEC 60027-2.)
@item YB
@cindex yottabyte, definition of
yottabyte: @math{10^{24} = 1,000,000,000,000,000,000,000,000}.
@item Y
@itemx YiB
@math{2^{80} = 1,208,925,819,614,629,174,706,176}.
(@samp{Yi} is a @acronym{GNU} extension to IEC 60027-2.)
@end table
@opindex -k
@opindex -h
@opindex --block-size
@opindex --human-readable
@opindex --si
Block size defaults can be overridden by an explicit
@option{--block-size=@var{size}} option. The @option{-k}
option is equivalent to @option{--block-size=1K}, which
is the default unless the @env{POSIXLY_CORRECT} environment variable is
set. The @option{-h} or @option{--human-readable} option is equivalent to
@option{--block-size=human-readable}. The @option{--si} option is
equivalent to @option{--block-size=si}.
@node Signal specifications
@section Signal specifications
@cindex signals, specifying
A @var{signal} may be a signal name like @samp{HUP}, or a signal
number like @samp{1}, or an exit status of a process terminated by the
signal. A signal name can be given in canonical form or prefixed by
@samp{SIG}. The case of the letters is ignored. The following signal names
and numbers are supported on all @acronym{POSIX} compliant systems:
@table @samp
@item HUP
1. Hangup.
@item INT
2. Terminal interrupt.
@item QUIT
3. Terminal quit.
@item ABRT
6. Process abort.
@item KILL
9. Kill (cannot be caught or ignored).
@item ALRM
14. Alarm Clock.
@item TERM
15. Termination.
@end table
@noindent
Other supported signal names have system-dependent corresponding
numbers. All systems conforming to @acronym{POSIX} 1003.1-2001 also
support the following signals:
@table @samp
@item BUS
Access to an undefined portion of a memory object.
@item CHLD
Child process terminated, stopped, or continued.
@item CONT
Continue executing, if stopped.
@item FPE
Erroneous arithmetic operation.
@item ILL
Illegal Instruction.
@item PIPE
Write on a pipe with no one to read it.
@item SEGV
Invalid memory reference.
@item STOP
Stop executing (cannot be caught or ignored).
@item TSTP
Terminal stop.
@item TTIN
Background process attempting read.
@item TTOU
Background process attempting write.
@item URG
High bandwidth data is available at a socket.
@item USR1
User-defined signal 1.
@item USR2
User-defined signal 2.
@end table
@noindent
@acronym{POSIX} 1003.1-2001 systems that support the @acronym{XSI} extension
also support the following signals:
@table @samp
@item POLL
Pollable event.
@item PROF
Profiling timer expired.
@item SYS
Bad system call.
@item TRAP
Trace/breakpoint trap.
@item VTALRM
Virtual timer expired.
@item XCPU
CPU time limit exceeded.
@item XFSZ
File size limit exceeded.
@end table
@noindent
@acronym{POSIX} 1003.1-2001 systems that support the @acronym{XRT} extension
also support at least eight real-time signals called @samp{RTMIN},
@samp{RTMIN+1}, @dots{}, @samp{RTMAX-1}, @samp{RTMAX}.
@node Disambiguating names and IDs
@section chown and chgrp: Disambiguating user names and IDs
@cindex user names, disambiguating
@cindex user IDs, disambiguating
@cindex group names, disambiguating
@cindex group IDs, disambiguating
@cindex disambiguating group names and IDs
Since the @var{owner} and @var{group} arguments to @command{chown} and
@command{chgrp} may be specified as names or numeric IDs, there is an
apparent ambiguity.
What if a user or group @emph{name} is a string of digits?
@footnote{Using a number as a user name is common in some environments.}
Should the command interpret it as a user name or as an ID?
@acronym{POSIX} requires that @command{chown} and @command{chgrp}
first attempt to resolve the specified string as a name, and
only once that fails, then try to interpret it as an ID.
This is troublesome when you want to specify a numeric ID, say 42,
and it must work even in a pathological situation where
@samp{42} is a user name that maps to some other user ID, say 1000.
Simply invoking @code{chown 42 F}, will set @file{F}s owner ID to
1000---not what you intended.
GNU @command{chown} and @command{chgrp} provide a way to work around this,
that at the same time may result in a significant performance improvement
by eliminating a database look-up.
Simply precede each numeric user ID and/or group ID with a @samp{+},
in order to force its interpretation as an integer:
@example
chown +42 F
chgrp +$numeric_group_id another-file
chown +0:+0 /
@end example
GNU @command{chown} and @command{chgrp}
skip the name look-up process for each @samp{+}-prefixed string,
because a string containing @samp{+} is never a valid user or group name.
This syntax is accepted on most common Unix systems, but not on Solaris 10.
@node Random sources
@section Sources of random data
@cindex random sources
The @command{shuf}, @command{shred}, and @command{sort} commands
sometimes need random data to do their work. For example, @samp{sort
-R} must choose a hash function at random, and it needs random data to
make this selection.
By default these commands use an internal pseudorandom generator
initialized by a small amount of entropy, but can be directed to use
an external source with the @option{--random-source=@var{file}} option.
An error is reported if @var{file} does not contain enough bytes.
For example, the device file @file{/dev/urandom} could be used as the
source of random data. Typically, this device gathers environmental
noise from device drivers and other sources into an entropy pool, and
uses the pool to generate random bits. If the pool is short of data,
the device reuses the internal pool to produce more bits, using a
cryptographically secure pseudorandom number generator. But be aware
that this device is not designed for bulk random data generation
and is relatively slow.
@file{/dev/urandom} suffices for most practical uses, but applications
requiring high-value or long-term protection of private data may
require an alternate data source like @file{/dev/random} or
@file{/dev/arandom}. The set of available sources depends on your
operating system.
To reproduce the results of an earlier invocation of a command, you
can save some random data into a file and then use that file as the
random source in earlier and later invocations of the command.
@node Target directory
@section Target directory
@cindex target directory
The @command{cp}, @command{install}, @command{ln}, and @command{mv}
commands normally treat the last operand specially when it is a
directory or a symbolic link to a directory. For example, @samp{cp
source dest} is equivalent to @samp{cp source dest/source} if
@file{dest} is a directory. Sometimes this behavior is not exactly
what is wanted, so these commands support the following options to
allow more fine-grained control:
@table @samp
@item -T
@itemx --no-target-directory
@opindex --no-target-directory
@cindex target directory
@cindex destination directory
Do not treat the last operand specially when it is a directory or a
symbolic link to a directory. This can help avoid race conditions in
programs that operate in a shared area. For example, when the command
@samp{mv /tmp/source /tmp/dest} succeeds, there is no guarantee that
@file{/tmp/source} was renamed to @file{/tmp/dest}: it could have been
renamed to @file{/tmp/dest/source} instead, if some other process
created @file{/tmp/dest} as a directory. However, if @file{mv
-T /tmp/source /tmp/dest} succeeds, there is no
question that @file{/tmp/source} was renamed to @file{/tmp/dest}.
In the opposite situation, where you want the last operand to be
treated as a directory and want a diagnostic otherwise, you can use
the @option{--target-directory} (@option{-t}) option.
@item -t @var{directory}
@itemx @w{@kbd{--target-directory}=@var{directory}}
@opindex --target-directory
@cindex target directory
@cindex destination directory
Use @var{directory} as the directory component of each destination
file name.
The interface for most programs is that after processing options and a
finite (possibly zero) number of fixed-position arguments, the remaining
argument list is either expected to be empty, or is a list of items
(usually files) that will all be handled identically. The @command{xargs}
program is designed to work well with this convention.
The commands in the @command{mv}-family are unusual in that they take
a variable number of arguments with a special case at the @emph{end}
(namely, the target directory). This makes it nontrivial to perform some
operations, e.g., ``move all files from here to ../d/'', because
@code{mv * ../d/} might exhaust the argument space, and @code{ls | xargs ...}
doesn't have a clean way to specify an extra final argument for each
invocation of the subject command. (It can be done by going through a
shell command, but that requires more human labor and brain power than
it should.)
The @w{@kbd{--target-directory}} (@option{-t}) option allows the @command{cp},
@command{install}, @command{ln}, and @command{mv} programs to be used
conveniently with @command{xargs}. For example, you can move the files
from the current directory to a sibling directory, @code{d} like this:
@smallexample
ls | xargs mv -t ../d --
@end smallexample
However, this doesn't move files whose names begin with @samp{.}.
If you use the @sc{gnu} @command{find} program, you can move those
files too, with this command:
@example
find . -mindepth 1 -maxdepth 1 \
| xargs mv -t ../d
@end example
But both of the above approaches fail if there are no files in the
current directory, or if any file has a name containing a blank or
some other special characters.
The following example removes those limitations and requires both
@sc{gnu} @command{find} and @sc{gnu} @command{xargs}:
@example
find . -mindepth 1 -maxdepth 1 -print0 \
| xargs --null --no-run-if-empty \
mv -t ../d
@end example
@end table
@noindent
The @option{--target-directory} (@option{-t}) and
@option{--no-target-directory} (@option{-T})
options cannot be combined.
@node Trailing slashes
@section Trailing slashes
@cindex trailing slashes
Some @sc{gnu} programs (at least @command{cp} and @command{mv}) allow you to
remove any trailing slashes from each @var{source} argument before
operating on it. The @w{@kbd{--strip-trailing-slashes}} option enables
this behavior.
This is useful when a @var{source} argument may have a trailing slash and
@c FIXME: mv's behavior in this case is system-dependent
specify a symbolic link to a directory. This scenario is in fact rather
common because some shells can automatically append a trailing slash when
performing file name completion on such symbolic links. Without this
option, @command{mv}, for example, (via the system's rename function) must
interpret a trailing slash as a request to dereference the symbolic link
and so must rename the indirectly referenced @emph{directory} and not
the symbolic link. Although it may seem surprising that such behavior
be the default, it is required by @acronym{POSIX} and is consistent with
other parts of that standard.
@node Traversing symlinks
@section Traversing symlinks
@cindex symbolic link to directory, controlling traversal of
The following options modify how @command{chown} and @command{chgrp}
@c FIXME: note that `du' has these options, too, but they have slightly
@c different meaning.
traverse a hierarchy when the @option{--recursive} (@option{-R})
option is also specified.
If more than one of the following options is specified, only the final
one takes effect.
These options specify whether processing a symbolic link to a directory
entails operating on just the symbolic link or on all files in the
hierarchy rooted at that directory.
These options are independent of @option{--dereference} and
@option{--no-dereference} (@option{-h}), which control whether to modify
a symlink or its referent.
@table @samp
@macro choptH
@item -H
@opindex -H
@cindex symbolic link to directory, traverse each that is specified on the command line
If @option{--recursive} (@option{-R}) is specified and
a command line argument is a symbolic link to a directory, traverse it.
@end macro
@choptH
@macro choptL
@item -L
@opindex -L
@cindex symbolic link to directory, traverse each that is encountered
In a recursive traversal, traverse every symbolic link to a directory
that is encountered.
@end macro
@choptL
@macro choptP
@item -P
@opindex -P
@cindex symbolic link to directory, never traverse
Do not traverse any symbolic links.
This is the default if none of @option{-H}, @option{-L},
or @option{-P} is specified.
@end macro
@choptP
@end table
@node Treating / specially
@section Treating @file{/} specially
Certain commands can operate destructively on entire hierarchies.
For example, if a user with appropriate privileges mistakenly runs
@samp{rm -rf / tmp/junk}, that may remove
all files on the entire system. Since there are so few
legitimate uses for such a command,
@sc{gnu} @command{rm} normally declines to operate on any directory
that resolves to @file{/}. If you really want to try to remove all
the files on your system, you can use the @option{--no-preserve-root}
option, but the default behavior, specified by the
@option{--preserve-option}, is safer for most purposes.
The commands @command{chgrp}, @command{chmod} and @command{chown}
can also operate destructively on entire hierarchies, so they too
support these options. Although, unlike @command{rm}, they don't
actually unlink files, these commands are arguably more dangerous
when operating recursively on @file{/}, since they often work much
more quickly, and hence damage more files before an alert user can
interrupt them. Tradition and @acronym{POSIX} require these commands
to operate recursively on @file{/}, so they default to
@option{--no-preserve-root}, but using the @option{--preserve-root}
option makes them safer for most purposes. For convenience you can
specify @option{--preserve-root} in an alias or in a shell function.
Note that the @option{--preserve-root} option also ensures
that @command{chgrp} and @command{chown} do not modify @file{/}
even when dereferencing a symlink pointing to @file{/}.
@node Special built-in utilities
@section Special built-in utilities
Some programs like @command{nice} can invoke other programs; for
example, the command @samp{nice cat file} invokes the program
@command{cat} by executing the command @samp{cat file}. However,
@dfn{special built-in utilities} like @command{exit} cannot be invoked
this way. For example, the command @samp{nice exit} does not have a
well-defined behavior: it may generate an error message instead of
exiting.
Here is a list of the special built-in utilities that are standardized
by @acronym{POSIX} 1003.1-2004.
@quotation
@t{.@: : break continue eval exec exit export readonly
return set shift times trap unset}
@end quotation
For example, because @samp{.}, @samp{:}, and @samp{exec} are special,
the commands @samp{nice . foo.sh}, @samp{nice :}, and @samp{nice exec
pwd} do not work as you might expect.
Many shells extend this list. For example, Bash has several extra
special built-in utilities like @command{history}, and
@command{suspend}, and with Bash the command @samp{nice suspend}
generates an error message instead of suspending.
@node Standards conformance
@section Standards conformance
@vindex POSIXLY_CORRECT
In a few cases, the @sc{gnu} utilities' default behavior is
incompatible with the @acronym{POSIX} standard. To suppress these
incompatibilities, define the @env{POSIXLY_CORRECT} environment
variable. Unless you are checking for @acronym{POSIX} conformance, you
probably do not need to define @env{POSIXLY_CORRECT}.
Newer versions of @acronym{POSIX} are occasionally incompatible with older
versions. For example, older versions of @acronym{POSIX} required the
command @samp{sort +1} to sort based on the second and succeeding
fields in each input line, but starting with @acronym{POSIX} 1003.1-2001
the same command is required to sort the file named @file{+1}, and you
must instead use the command @samp{sort -k 2} to get the field-based
sort.
@vindex _POSIX2_VERSION
The @sc{gnu} utilities normally conform to the version of @acronym{POSIX}
that is standard for your system. To cause them to conform to a
different version of @acronym{POSIX}, define the @env{_POSIX2_VERSION}
environment variable to a value of the form @var{yyyymm} specifying
the year and month the standard was adopted. Two values are currently
supported for @env{_POSIX2_VERSION}: @samp{199209} stands for
@acronym{POSIX} 1003.2-1992, and @samp{200112} stands for @acronym{POSIX}
1003.1-2001. For example, if you have a newer system but are running software
that assumes an older version of @acronym{POSIX} and uses @samp{sort +1}
or @samp{tail +10}, you can work around any compatibility problems by setting
@samp{_POSIX2_VERSION=199209} in your environment.
@node Output of entire files
@chapter Output of entire files
@cindex output of entire files
@cindex entire files, output of
These commands read and write entire files, possibly transforming them
in some way.
@menu
* cat invocation:: Concatenate and write files.
* tac invocation:: Concatenate and write files in reverse.
* nl invocation:: Number lines and write files.
* od invocation:: Write files in octal or other formats.
* base64 invocation:: Transform data into printable data.
@end menu
@node cat invocation
@section @command{cat}: Concatenate and write files
@pindex cat
@cindex concatenate and write files
@cindex copying files
@command{cat} copies each @var{file} (@samp{-} means standard input), or
standard input if none are given, to standard output. Synopsis:
@example
cat [@var{option}] [@var{file}]@dots{}
@end example
The program accepts the following options. Also see @ref{Common options}.
@table @samp
@item -A
@itemx --show-all
@opindex -A
@opindex --show-all
Equivalent to @option{-vET}.
@item -b
@itemx --number-nonblank
@opindex -b
@opindex --number-nonblank
Number all nonempty output lines, starting with 1.
@item -e
@opindex -e
Equivalent to @option{-vE}.
@item -E
@itemx --show-ends
@opindex -E
@opindex --show-ends
Display a @samp{$} after the end of each line.
@item -n
@itemx --number
@opindex -n
@opindex --number
Number all output lines, starting with 1. This option is ignored
if @option{-b} is in effect.
@item -s
@itemx --squeeze-blank
@opindex -s
@opindex --squeeze-blank
@cindex squeezing empty lines
Suppress repeated adjacent empty lines; output just one empty line
instead of several.
@item -t
@opindex -t
Equivalent to @option{-vT}.
@item -T
@itemx --show-tabs
@opindex -T
@opindex --show-tabs
Display TAB characters as @samp{^I}.
@item -u
@opindex -u
Ignored; for @acronym{POSIX} compatibility.
@item -v
@itemx --show-nonprinting
@opindex -v
@opindex --show-nonprinting
Display control characters except for LFD and TAB using
@samp{^} notation and precede characters that have the high bit set with
@samp{M-}.
@end table
On systems like MS-DOS that distinguish between text and binary files,
@command{cat} normally reads and writes in binary mode. However,
@command{cat} reads in text mode if one of the options
@option{-bensAE} is used or if @command{cat} is reading from standard
input and standard input is a terminal. Similarly, @command{cat}
writes in text mode if one of the options @option{-bensAE} is used or
if standard output is a terminal.
@exitstatus
Examples:
@smallexample
# Output f's contents, then standard input, then g's contents.
cat f - g
# Copy standard input to standard output.
cat
@end smallexample
@node tac invocation
@section @command{tac}: Concatenate and write files in reverse
@pindex tac
@cindex reversing files
@command{tac} copies each @var{file} (@samp{-} means standard input), or
standard input if none are given, to standard output, reversing the
records (lines by default) in each separately. Synopsis:
@example
tac [@var{option}]@dots{} [@var{file}]@dots{}
@end example
@dfn{Records} are separated by instances of a string (newline by
default). By default, this separator string is attached to the end of
the record that it follows in the file.
The program accepts the following options. Also see @ref{Common options}.
@table @samp
@item -b
@itemx --before
@opindex -b
@opindex --before
The separator is attached to the beginning of the record that it
precedes in the file.
@item -r
@itemx --regex
@opindex -r
@opindex --regex
Treat the separator string as a regular expression. Users of @command{tac}
on MS-DOS/MS-Windows should note that, since @command{tac} reads files in
binary mode, each line of a text file might end with a CR/LF pair
instead of the Unix-style LF.
@item -s @var{separator}
@itemx --separator=@var{separator}
@opindex -s
@opindex --separator
Use @var{separator} as the record separator, instead of newline.
@end table
@exitstatus
@node nl invocation
@section @command{nl}: Number lines and write files
@pindex nl
@cindex numbering lines
@cindex line numbering
@command{nl} writes each @var{file} (@samp{-} means standard input), or
standard input if none are given, to standard output, with line numbers
added to some or all of the lines. Synopsis:
@example
nl [@var{option}]@dots{} [@var{file}]@dots{}
@end example
@cindex logical pages, numbering on
@command{nl} decomposes its input into (logical) pages; by default, the
line number is reset to 1 at the top of each logical page. @command{nl}
treats all of the input files as a single document; it does not reset
line numbers or logical pages between files.
@cindex headers, numbering
@cindex body, numbering
@cindex footers, numbering
A logical page consists of three sections: header, body, and footer.
Any of the sections can be empty. Each can be numbered in a different
style from the others.
The beginnings of the sections of logical pages are indicated in the
input file by a line containing exactly one of these delimiter strings:
@table @samp
@item \:\:\:
start of header;
@item \:\:
start of body;
@item \:
start of footer.
@end table
The two characters from which these strings are made can be changed from
@samp{\} and @samp{:} via options (see below), but the pattern and
length of each string cannot be changed.
A section delimiter is replaced by an empty line on output. Any text
that comes before the first section delimiter string in the input file
is considered to be part of a body section, so @command{nl} treats a
file that contains no section delimiters as a single body section.
The program accepts the following options. Also see @ref{Common options}.
@table @samp
@item -b @var{style}
@itemx --body-numbering=@var{style}
@opindex -b
@opindex --body-numbering
Select the numbering style for lines in the body section of each
logical page. When a line is not numbered, the current line number
is not incremented, but the line number separator character is still
prepended to the line. The styles are:
@table @samp
@item a
number all lines,
@item t
number only nonempty lines (default for body),
@item n
do not number lines (default for header and footer),
@item p@var{bre}
number only lines that contain a match for the basic regular
expression @var{bre}.
@xref{Regular Expressions, , Regular Expressions, grep, The GNU Grep Manual}.
@end table
@item -d @var{cd}
@itemx --section-delimiter=@var{cd}
@opindex -d
@opindex --section-delimiter
@cindex section delimiters of pages
Set the section delimiter characters to @var{cd}; default is
@samp{\:}. If only @var{c} is given, the second remains @samp{:}.
(Remember to protect @samp{\} or other metacharacters from shell
expansion with quotes or extra backslashes.)
@item -f @var{style}
@itemx --footer-numbering=@var{style}
@opindex -f
@opindex --footer-numbering
Analogous to @option{--body-numbering}.
@item -h @var{style}
@itemx --header-numbering=@var{style}
@opindex -h
@opindex --header-numbering
Analogous to @option{--body-numbering}.
@item -i @var{number}
@itemx --line-increment=@var{number}
@opindex -i
@opindex --line-increment
Increment line numbers by @var{number} (default 1).
@item -l @var{number}
@itemx --join-blank-lines=@var{number}
@opindex -l
@opindex --join-blank-lines
@cindex empty lines, numbering
@cindex blank lines, numbering
Consider @var{number} (default 1) consecutive empty lines to be one
logical line for numbering, and only number the last one. Where fewer
than @var{number} consecutive empty lines occur, do not number them.
An empty line is one that contains no characters, not even spaces
or tabs.
@item -n @var{format}
@itemx --number-format=@var{format}
@opindex -n
@opindex --number-format
Select the line numbering format (default is @code{rn}):
@table @samp
@item ln
@opindex ln @r{format for @command{nl}}
left justified, no leading zeros;
@item rn
@opindex rn @r{format for @command{nl}}
right justified, no leading zeros;
@item rz
@opindex rz @r{format for @command{nl}}
right justified, leading zeros.
@end table
@item -p
@itemx --no-renumber
@opindex -p
@opindex --no-renumber
Do not reset the line number at the start of a logical page.
@item -s @var{string}
@itemx --number-separator=@var{string}
@opindex -s
@opindex --number-separator
Separate the line number from the text line in the output with
@var{string} (default is the TAB character).
@item -v @var{number}
@itemx --starting-line-number=@var{number}
@opindex -v
@opindex --starting-line-number
Set the initial line number on each logical page to @var{number} (default 1).
@item -w @var{number}
@itemx --number-width=@var{number}
@opindex -w
@opindex --number-width
Use @var{number} characters for line numbers (default 6).
@end table
@exitstatus
@node od invocation
@section @command{od}: Write files in octal or other formats
@pindex od
@cindex octal dump of files
@cindex hex dump of files
@cindex ASCII dump of files
@cindex file contents, dumping unambiguously
@command{od} writes an unambiguous representation of each @var{file}
(@samp{-} means standard input), or standard input if none are given.
Synopses:
@smallexample
od [@var{option}]@dots{} [@var{file}]@dots{}
od [-abcdfilosx]@dots{} [@var{file}] [[+]@var{offset}[.][b]]
od [@var{option}]@dots{} --traditional [@var{file}] [[+]@var{offset}[.][b] [[+]@var{label}[.][b]]]
@end smallexample
Each line of output consists of the offset in the input, followed by
groups of data from the file. By default, @command{od} prints the offset in
octal, and each group of file data is a C @code{short int}'s worth of input
printed as a single octal number.
If @var{offset} is given, it specifies how many input bytes to skip
before formatting and writing. By default, it is interpreted as an
octal number, but the optional trailing decimal point causes it to be
interpreted as decimal. If no decimal is specified and the offset
begins with @samp{0x} or @samp{0X} it is interpreted as a hexadecimal
number. If there is a trailing @samp{b}, the number of bytes skipped
will be @var{offset} multiplied by 512.
If a command is of both the first and second forms, the second form is
assumed if the last operand begins with @samp{+} or (if there are two
operands) a digit. For example, in @samp{od foo 10} and @samp{od +10}
the @samp{10} is an offset, whereas in @samp{od 10} the @samp{10} is a
file name.
The program accepts the following options. Also see @ref{Common options}.
@table @samp
@item -A @var{radix}
@itemx --address-radix=@var{radix}
@opindex -A
@opindex --address-radix
@cindex radix for file offsets
@cindex file offset radix
Select the base in which file offsets are printed. @var{radix} can
be one of the following:
@table @samp
@item d
decimal;
@item o
octal;
@item x
hexadecimal;
@item n
none (do not print offsets).
@end table
The default is octal.
@item -j @var{bytes}
@itemx --skip-bytes=@var{bytes}
@opindex -j
@opindex --skip-bytes
Skip @var{bytes} input bytes before formatting and writing. If
@var{bytes} begins with @samp{0x} or @samp{0X}, it is interpreted in
hexadecimal; otherwise, if it begins with @samp{0}, in octal; otherwise,
in decimal.
@multiplierSuffixes{bytes}
@item -N @var{bytes}
@itemx --read-bytes=@var{bytes}
@opindex -N
@opindex --read-bytes
Output at most @var{bytes} bytes of the input. Prefixes and suffixes on
@code{bytes} are interpreted as for the @option{-j} option.
@item -S @var{bytes}
@itemx --strings[=@var{bytes}]
@opindex -S
@opindex --strings
@cindex string constants, outputting
Instead of the normal output, output only @dfn{string constants}: at
least @var{bytes} consecutive @acronym{ASCII} graphic characters,
followed by a zero byte (@acronym{ASCII} @sc{nul}).
Prefixes and suffixes on @code{bytes} are interpreted as for the
@option{-j} option.
If @var{n} is omitted with @option{--strings}, the default is 3.
@item -t @var{type}
@itemx --format=@var{type}
@opindex -t
@opindex --format
Select the format in which to output the file data. @var{type} is a
string of one or more of the below type indicator characters. If you
include more than one type indicator character in a single @var{type}
string, or use this option more than once, @command{od} writes one copy
of each output line using each of the data types that you specified,
in the order that you specified.
Adding a trailing ``z'' to any type specification appends a display
of the @acronym{ASCII} character representation of the printable characters
to the output line generated by the type specification.
@table @samp
@item a
named character, ignoring high-order bit
@item c
@acronym{ASCII} character or backslash escape,
@item d
signed decimal
@item f
floating point
@item o
octal
@item u
unsigned decimal
@item x
hexadecimal
@end table
The type @code{a} outputs things like @samp{sp} for space, @samp{nl} for
newline, and @samp{nul} for a zero byte. Only the least significant
seven bits of each byte is used; the high-order bit is ignored.
Type @code{c} outputs
@samp{ }, @samp{\n}, and @code{\0}, respectively.
@cindex type size
Except for types @samp{a} and @samp{c}, you can specify the number
of bytes to use in interpreting each number in the given data type
by following the type indicator character with a decimal integer.
Alternately, you can specify the size of one of the C compiler's
built-in data types by following the type indicator character with
one of the following characters. For integers (@samp{d}, @samp{o},
@samp{u}, @samp{x}):
@table @samp
@item C
char
@item S
short
@item I
int
@item L
long
@end table
For floating point (@code{f}):
@table @asis
@item F
float
@item D
double
@item L
long double
@end table
@item -v
@itemx --output-duplicates
@opindex -v
@opindex --output-duplicates
Output consecutive lines that are identical. By default, when two or
more consecutive output lines would be identical, @command{od} outputs only
the first line, and puts just an asterisk on the following line to
indicate the elision.
@item -w[@var{n}]
@itemx --width[=@var{n}]
@opindex -w
@opindex --width
Dump @code{n} input bytes per output line. This must be a multiple of
the least common multiple of the sizes associated with the specified
output types.
If this option is not given at all, the default is 16. If @var{n} is
omitted, the default is 32.
@end table
The next several options are shorthands for format specifications.
@sc{gnu} @command{od} accepts any combination of shorthands and format
specification options. These options accumulate.
@table @samp
@item -a
@opindex -a
Output as named characters. Equivalent to @samp{-t a}.
@item -b
@opindex -b
Output as octal bytes. Equivalent to @samp{-t o1}.
@item -c
@opindex -c
Output as @acronym{ASCII} characters or backslash escapes. Equivalent to
@samp{-t c}.
@item -d
@opindex -d
Output as unsigned decimal two-byte units. Equivalent to @samp{-t u2}.
@item -f
@opindex -f
Output as floats. Equivalent to @samp{-t fF}.
@item -i
@opindex -i
Output as decimal ints. Equivalent to @samp{-t dI}.
@item -l
@opindex -l
Output as decimal long ints. Equivalent to @samp{-t dL}.
@item -o
@opindex -o
Output as octal two-byte units. Equivalent to @option{-t o2}.
@item -s
@opindex -s
Output as decimal two-byte units. Equivalent to @option{-t d2}.
@item -x
@opindex -x
Output as hexadecimal two-byte units. Equivalent to @samp{-t x2}.
@item --traditional
@opindex --traditional
Recognize the non-option label argument that traditional @command{od}
accepted. The following syntax:
@smallexample
od --traditional [@var{file}] [[+]@var{offset}[.][b] [[+]@var{label}[.][b]]]
@end smallexample
@noindent
can be used to specify at most one file and optional arguments
specifying an offset and a pseudo-start address, @var{label}.
The @var{label} argument is interpreted
just like @var{offset}, but it specifies an initial pseudo-address. The
pseudo-addresses are displayed in parentheses following any normal
address.
@end table
@exitstatus
@node base64 invocation
@section @command{base64}: Transform data into printable data
@pindex base64
@cindex base64 encoding
@command{base64} transforms data read from a file, or standard input,
into (or from) base64 encoded form. The base64 encoded form uses
printable @acronym{ASCII} characters to represent binary data.
Synopses:
@smallexample
base64 [@var{option}]@dots{} [@var{file}]
base64 --decode [@var{option}]@dots{} [@var{file}]
@end smallexample
The base64 encoding expands data to roughly 133% of the original.
The format conforms to
@uref{ftp://ftp.rfc-editor.org/in-notes/rfc4648.txt, RFC 4648}.
The program accepts the following options. Also see @ref{Common options}.
@table @samp
@item -w @var{cols}
@itemx --wrap=@var{cols}
@opindex -w
@opindex --wrap
@cindex wrap data
@cindex column to wrap data after
During encoding, wrap lines after @var{cols} characters. This must be
a positive number.
The default is to wrap after 76 characters. Use the value 0 to
disable line wrapping altogether.
@item -d
@itemx --decode
@opindex -d
@opindex --decode
@cindex Decode base64 data
@cindex Base64 decoding
Change the mode of operation, from the default of encoding data, to
decoding data. Input is expected to be base64 encoded data, and the
output will be the original data.
@item -i
@itemx --ignore-garbage
@opindex -i
@opindex --ignore-garbage
@cindex Ignore garbage in base64 stream
When decoding, newlines are always accepted.
During decoding, ignore unrecognized bytes,
to permit distorted data to be decoded.
@end table
@exitstatus
@node Formatting file contents
@chapter Formatting file contents
@cindex formatting file contents
These commands reformat the contents of files.
@menu
* fmt invocation:: Reformat paragraph text.
* pr invocation:: Paginate or columnate files for printing.
* fold invocation:: Wrap input lines to fit in specified width.
@end menu
@node fmt invocation
@section @command{fmt}: Reformat paragraph text
@pindex fmt
@cindex reformatting paragraph text
@cindex paragraphs, reformatting
@cindex text, reformatting
@command{fmt} fills and joins lines to produce output lines of (at most)
a given number of characters (75 by default). Synopsis:
@example
fmt [@var{option}]@dots{} [@var{file}]@dots{}
@end example
@command{fmt} reads from the specified @var{file} arguments (or standard
input if none are given), and writes to standard output.
By default, blank lines, spaces between words, and indentation are
preserved in the output; successive input lines with different
indentation are not joined; tabs are expanded on input and introduced on
output.
@cindex line-breaking
@cindex sentences and line-breaking
@cindex Knuth, Donald E.
@cindex Plass, Michael F.
@command{fmt} prefers breaking lines at the end of a sentence, and tries to
avoid line breaks after the first word of a sentence or before the last
word of a sentence. A @dfn{sentence break} is defined as either the end
of a paragraph or a word ending in any of @samp{.?!}, followed by two
spaces or end of line, ignoring any intervening parentheses or quotes.
Like @TeX{}, @command{fmt} reads entire ``paragraphs'' before choosing line
breaks; the algorithm is a variant of that given by Donald E. Knuth
and Michael F. Plass in ``Breaking Paragraphs Into Lines'',
@cite{Software---Practice & Experience} @b{11}, 11 (November 1981),
1119--1184.
The program accepts the following options. Also see @ref{Common options}.
@table @samp
@item -c
@itemx --crown-margin
@opindex -c
@opindex --crown-margin
@cindex crown margin
@dfn{Crown margin} mode: preserve the indentation of the first two
lines within a paragraph, and align the left margin of each subsequent
line with that of the second line.
@item -t
@itemx --tagged-paragraph
@opindex -t
@opindex --tagged-paragraph
@cindex tagged paragraphs
@dfn{Tagged paragraph} mode: like crown margin mode, except that if
indentation of the first line of a paragraph is the same as the
indentation of the second, the first line is treated as a one-line
paragraph.
@item -s
@itemx --split-only
@opindex -s
@opindex --split-only
Split lines only. Do not join short lines to form longer ones. This
prevents sample lines of code, and other such ``formatted'' text from
being unduly combined.
@item -u
@itemx --uniform-spacing
@opindex -u
@opindex --uniform-spacing
Uniform spacing. Reduce spacing between words to one space, and spacing
between sentences to two spaces.
@item -@var{width}
@itemx -w @var{width}
@itemx --width=@var{width}
@opindex -@var{width}
@opindex -w
@opindex --width
Fill output lines up to @var{width} characters (default 75). @command{fmt}
initially tries to make lines about 7% shorter than this, to give it
room to balance line lengths.
@item -p @var{prefix}
@itemx --prefix=@var{prefix}
Only lines beginning with @var{prefix} (possibly preceded by whitespace)
are subject to formatting. The prefix and any preceding whitespace are
stripped for the formatting and then re-attached to each formatted output
line. One use is to format certain kinds of program comments, while
leaving the code unchanged.
@end table
@exitstatus
@node pr invocation
@section @command{pr}: Paginate or columnate files for printing
@pindex pr
@cindex printing, preparing files for
@cindex multicolumn output, generating
@cindex merging files in parallel
@command{pr} writes each @var{file} (@samp{-} means standard input), or
standard input if none are given, to standard output, paginating and
optionally outputting in multicolumn format; optionally merges all
@var{file}s, printing all in parallel, one per column. Synopsis:
@example
pr [@var{option}]@dots{} [@var{file}]@dots{}
@end example
@vindex LC_MESSAGES
By default, a 5-line header is printed at each page: two blank lines;
a line with the date, the file name, and the page count; and two more
blank lines. A footer of five blank lines is also printed.
The default @var{page_length} is 66
lines. The default number of text lines is therefore 56.
The text line of the header takes the form
@samp{@var{date} @var{string} @var{page}}, with spaces inserted around
@var{string} so that the line takes up the full @var{page_width}. Here,
@var{date} is the date (see the @option{-D} or @option{--date-format}
option for details), @var{string} is the centered header string, and
@var{page} identifies the page number. The @env{LC_MESSAGES} locale
category affects the spelling of @var{page}; in the default C locale, it
is @samp{Page @var{number}} where @var{number} is the decimal page
number.
Form feeds in the input cause page breaks in the output. Multiple form
feeds produce empty pages.
Columns are of equal width, separated by an optional string (default
is @samp{space}). For multicolumn output, lines will always be truncated to
@var{page_width} (default 72), unless you use the @option{-J} option.
For single
column output no line truncation occurs by default. Use @option{-W} option to
truncate lines in that case.
The following changes were made in version 1.22i and apply to later
versions of @command{pr}:
@c FIXME: this whole section here sounds very awkward to me. I
@c made a few small changes, but really it all needs to be redone. - Brian
@c OK, I fixed another sentence or two, but some of it I just don't understand.
@ - Brian
@itemize @bullet
@item
Some small @var{letter options} (@option{-s}, @option{-w}) have been
redefined for better @acronym{POSIX} compliance. The output of some further
cases has been adapted to other Unix systems. These changes are not
compatible with earlier versions of the program.
@item
Some @var{new capital letter} options (@option{-J}, @option{-S}, @option{-W})
have been introduced to turn off unexpected interferences of small letter
options. The @option{-N} option and the second argument @var{last_page}
of @samp{+FIRST_PAGE} offer more flexibility. The detailed handling of
form feeds set in the input files requires the @option{-T} option.
@item
Capital letter options override small letter ones.
@item
Some of the option-arguments (compare @option{-s}, @option{-e},
@option{-i}, @option{-n}) cannot be specified as separate arguments from the
preceding option letter (already stated in the @acronym{POSIX} specification).
@end itemize
The program accepts the following options. Also see @ref{Common options}.
@table @samp
@item +@var{first_page}[:@var{last_page}]
@itemx --pages=@var{first_page}[:@var{last_page}]
@c The two following @opindex lines evoke warnings because they contain `:'
@c The `info' spec does not permit that. If we use those lines, we end
@c up with truncated index entries that don't work.
@c @opindex +@var{first_page}[:@var{last_page}]
@c @opindex --pages=@var{first_page}[:@var{last_page}]
@opindex +@var{page_range}
@opindex --pages=@var{page_range}
Begin printing with page @var{first_page} and stop with @var{last_page}.
Missing @samp{:@var{last_page}} implies end of file. While estimating
the number of skipped pages each form feed in the input file results
in a new page. Page counting with and without @samp{+@var{first_page}}
is identical. By default, counting starts with the first page of input
file (not first page printed). Line numbering may be altered by @option{-N}
option.
@item -@var{column}
@itemx --columns=@var{column}
@opindex -@var{column}
@opindex --columns
@cindex down columns
With each single @var{file}, produce @var{column} columns of output
(default is 1) and print columns down, unless @option{-a} is used. The
column width is automatically decreased as @var{column} increases; unless
you use the @option{-W/-w} option to increase @var{page_width} as well.
This option might well cause some lines to be truncated. The number of
lines in the columns on each page are balanced. The options @option{-e}
and @option{-i} are on for multiple text-column output. Together with
@option{-J} option column alignment and line truncation is turned off.
Lines of full length are joined in a free field format and @option{-S}
option may set field separators. @option{-@var{column}} may not be used
with @option{-m} option.
@item -a
@itemx --across
@opindex -a
@opindex --across
@cindex across columns
With each single @var{file}, print columns across rather than down. The
@option{-@var{column}} option must be given with @var{column} greater than one.
If a line is too long to fit in a column, it is truncated.
@item -c
@itemx --show-control-chars
@opindex -c
@opindex --show-control-chars
Print control characters using hat notation (e.g., @samp{^G}); print
other nonprinting characters in octal backslash notation. By default,
nonprinting characters are not changed.
@item -d
@itemx --double-space
@opindex -d
@opindex --double-space
@cindex double spacing
Double space the output.
@item -D @var{format}
@itemx --date-format=@var{format}
@cindex time formats
@cindex formatting times
Format header dates using @var{format}, using the same conventions as
for the command @samp{date +@var{format}}; @xref{date invocation}.
Except for directives, which start with
@samp{%}, characters in @var{format} are printed unchanged. You can use
this option to specify an arbitrary string in place of the header date,
e.g., @option{--date-format="Monday morning"}.
@vindex POSIXLY_CORRECT
@vindex LC_TIME
The default date format is @samp{%Y-%m-%d %H:%M} (for example,
@samp{2001-12-04 23:59});
but if the @env{POSIXLY_CORRECT} environment variable is set
and the @env{LC_TIME} locale category specifies the @acronym{POSIX}
locale, the default is @samp{%b %e %H:%M %Y} (for example,
@samp{Dec@ @ 4 23:59 2001}.
@vindex TZ
Time stamps are listed according to the time zone rules specified by
the @env{TZ} environment variable, or by the system default rules if
@env{TZ} is not set. @xref{TZ Variable,, Specifying the Time Zone
with @env{TZ}, libc, The GNU C Library Reference Manual}.
@item -e[@var{in-tabchar}[@var{in-tabwidth}]]
@itemx --expand-tabs[=@var{in-tabchar}[@var{in-tabwidth}]]
@opindex -e
@opindex --expand-tabs
@cindex input tabs
Expand @var{tab}s to spaces on input. Optional argument @var{in-tabchar} is
the input tab character (default is the TAB character). Second optional
argument @var{in-tabwidth} is the input tab character's width (default
is 8).
@item -f
@itemx -F
@itemx --form-feed
@opindex -F
@opindex -f
@opindex --form-feed
Use a form feed instead of newlines to separate output pages. This does
not alter the default page length of 66 lines.
@item -h @var{header}
@itemx --header=@var{header}
@opindex -h
@opindex --header
Replace the file name in the header with the centered string @var{header}.
When using the shell, @var{header} should be quoted and should be
separated from @option{-h} by a space.
@item -i[@var{out-tabchar}[@var{out-tabwidth}]]
@itemx --output-tabs[=@var{out-tabchar}[@var{out-tabwidth}]]
@opindex -i
@opindex --output-tabs
@cindex output tabs
Replace spaces with @var{tab}s on output. Optional argument @var{out-tabchar}
is the output tab character (default is the TAB character). Second optional
argument @var{out-tabwidth} is the output tab character's width (default
is 8).
@item -J
@itemx --join-lines
@opindex -J
@opindex --join-lines
Merge lines of full length. Used together with the column options
@option{-@var{column}}, @option{-a -@var{column}} or @option{-m}. Turns off
@option{-W/-w} line truncation;
no column alignment used; may be used with
@option{--sep-string[=@var{string}]}. @option{-J} has been introduced
(together with @option{-W} and @option{--sep-string})
to disentangle the old (@acronym{POSIX}-compliant) options @option{-w} and
@option{-s} along with the three column options.
@item -l @var{page_length}
@itemx --length=@var{page_length}
@opindex -l
@opindex --length
Set the page length to @var{page_length} (default 66) lines, including
the lines of the header [and the footer]. If @var{page_length} is less
than or equal to 10, the header and footer are omitted, as if the
@option{-t} option had been given.
@item -m
@itemx --merge
@opindex -m
@opindex --merge
Merge and print all @var{file}s in parallel, one in each column. If a
line is too long to fit in a column, it is truncated, unless the @option{-J}
option is used. @option{--sep-string[=@var{string}]} may be used.
Empty pages in
some @var{file}s (form feeds set) produce empty columns, still marked
by @var{string}. The result is a continuous line numbering and column
marking throughout the whole merged file. Completely empty merged pages
show no separators or line numbers. The default header becomes
@samp{@var{date} @var{page}} with spaces inserted in the middle; this
may be used with the @option{-h} or @option{--header} option to fill up
the middle blank part.
@item -n[@var{number-separator}[@var{digits}]]
@itemx --number-lines[=@var{number-separator}[@var{digits}]]
@opindex -n
@opindex --number-lines
Provide @var{digits} digit line numbering (default for @var{digits} is
5). With multicolumn output the number occupies the first @var{digits}
column positions of each text column or only each line of @option{-m}
output. With single column output the number precedes each line just as
@option{-m} does. Default counting of the line numbers starts with the
first line of the input file (not the first line printed, compare the
@option{--page} option and @option{-N} option).
Optional argument @var{number-separator} is the character appended to
the line number to separate it from the text followed. The default
separator is the TAB character. In a strict sense a TAB is always
printed with single column output only. The TAB width varies
with the TAB position, e.g., with the left @var{margin} specified
by @option{-o} option. With multicolumn output priority is given to
@samp{equal width of output columns} (a @acronym{POSIX} specification).
The TAB width is fixed to the value of the first column and does
not change with different values of left @var{margin}. That means a
fixed number of spaces is always printed in the place of the
@var{number-separator} TAB. The tabification depends upon the output
position.
@item -N @var{line_number}
@itemx --first-line-number=@var{line_number}
@opindex -N
@opindex --first-line-number
Start line counting with the number @var{line_number} at first line of
first page printed (in most cases not the first line of the input file).
@item -o @var{margin}
@itemx --indent=@var{margin}
@opindex -o
@opindex --indent
@cindex indenting lines
@cindex left margin
Indent each line with a margin @var{margin} spaces wide (default is zero).
The total page width is the size of the margin plus the @var{page_width}
set with the @option{-W/-w} option. A limited overflow may occur with
numbered single column output (compare @option{-n} option).
@item -r
@itemx --no-file-warnings
@opindex -r
@opindex --no-file-warnings
Do not print a warning message when an argument @var{file} cannot be
opened. (The exit status will still be nonzero, however.)
@item -s[@var{char}]
@itemx --separator[=@var{char}]
@opindex -s
@opindex --separator
Separate columns by a single character @var{char}. The default for
@var{char} is the TAB character without @option{-w} and @samp{no
character} with @option{-w}. Without @option{-s} the default separator
@samp{space} is set. @option{-s[char]} turns off line truncation of all
three column options (@option{-COLUMN}|@option{-a -COLUMN}|@option{-m}) unless
@option{-w} is set. This is a @acronym{POSIX}-compliant formulation.
@item -S@var{string}
@itemx --sep-string[=@var{string}]
@opindex -S
@opindex --sep-string
Use @var{string} to separate output columns. The @option{-S} option doesn't
affect the @option{-W/-w} option, unlike the @option{-s} option which does. It
does not affect line truncation or column alignment.
Without @option{-S}, and with @option{-J}, @command{pr} uses the default output
separator, TAB@.
Without @option{-S} or @option{-J}, @command{pr} uses a @samp{space}
(same as @option{-S"@w{ }"}). @option{--sep-string} with no
@samp{=@var{string}} is equivalent to @option{--sep-string=""}.
@item -t
@itemx --omit-header
@opindex -t
@opindex --omit-header
Do not print the usual header [and footer] on each page, and do not fill
out the bottom of pages (with blank lines or a form feed). No page
structure is produced, but form feeds set in the input files are retained.
The predefined pagination is not changed. @option{-t} or @option{-T} may be
useful together with other options; e.g.: @option{-t -e4}, expand TAB characters
in the input file to 4 spaces but don't make any other changes. Use of
@option{-t} overrides @option{-h}.
@item -T
@itemx --omit-pagination
@opindex -T
@opindex --omit-pagination
Do not print header [and footer]. In addition eliminate all form feeds
set in the input files.
@item -v
@itemx --show-nonprinting
@opindex -v
@opindex --show-nonprinting
Print nonprinting characters in octal backslash notation.
@item -w @var{page_width}
@itemx --width=@var{page_width}
@opindex -w
@opindex --width
Set page width to @var{page_width} characters for multiple text-column
output only (default for @var{page_width} is 72). @option{-s[CHAR]} turns
off the default page width and any line truncation and column alignment.
Lines of full length are merged, regardless of the column options
set. No @var{page_width} setting is possible with single column output.
A @acronym{POSIX}-compliant formulation.
@item -W @var{page_width}
@itemx --page_width=@var{page_width}
@opindex -W
@opindex --page_width
Set the page width to @var{page_width} characters. That's valid with and
without a column option. Text lines are truncated, unless @option{-J}
is used. Together with one of the three column options
(@option{-@var{column}}, @option{-a -@var{column}} or @option{-m}) column
alignment is always used. The separator options @option{-S} or @option{-s}
don't affect the @option{-W} option. Default is 72 characters. Without
@option{-W @var{page_width}} and without any of the column options NO line
truncation is used (defined to keep downward compatibility and to meet
most frequent tasks). That's equivalent to @option{-W 72 -J}. The header
line is never truncated.
@end table
@exitstatus
@node fold invocation
@section @command{fold}: Wrap input lines to fit in specified width
@pindex fold
@cindex wrapping long input lines
@cindex folding long input lines
@command{fold} writes each @var{file} (@option{-} means standard input), or
standard input if none are given, to standard output, breaking long
lines. Synopsis:
@example
fold [@var{option}]@dots{} [@var{file}]@dots{}
@end example
By default, @command{fold} breaks lines wider than 80 columns. The output
is split into as many lines as necessary.
@cindex screen columns
@command{fold} counts screen columns by default; thus, a tab may count more
than one column, backspace decreases the column count, and carriage
return sets the column to zero.
The program accepts the following options. Also see @ref{Common options}.
@table @samp
@item -b
@itemx --bytes
@opindex -b
@opindex --bytes
Count bytes rather than columns, so that tabs, backspaces, and carriage
returns are each counted as taking up one column, just like other
characters.
@item -s
@itemx --spaces
@opindex -s
@opindex --spaces
Break at word boundaries: the line is broken after the last blank before
the maximum line length. If the line contains no such blanks, the line
is broken at the maximum line length as usual.
@item -w @var{width}
@itemx --width=@var{width}
@opindex -w
@opindex --width
Use a maximum line length of @var{width} columns instead of 80.
For compatibility @command{fold} supports an obsolete option syntax
@option{-@var{width}}. New scripts should use @option{-w @var{width}}
instead.
@end table
@exitstatus
@node Output of parts of files
@chapter Output of parts of files
@cindex output of parts of files
@cindex parts of files, output of
These commands output pieces of the input.
@menu
* head invocation:: Output the first part of files.
* tail invocation:: Output the last part of files.
* split invocation:: Split a file into fixed-size pieces.
* csplit invocation:: Split a file into context-determined pieces.
@end menu
@node head invocation
@section @command{head}: Output the first part of files
@pindex head
@cindex initial part of files, outputting
@cindex first part of files, outputting
@command{head} prints the first part (10 lines by default) of each
@var{file}; it reads from standard input if no files are given or
when given a @var{file} of @option{-}. Synopsis:
@example
head [@var{option}]@dots{} [@var{file}]@dots{}
@end example
If more than one @var{file} is specified, @command{head} prints a
one-line header consisting of:
@example
==> @var{file name} <==
@end example
@noindent
before the output for each @var{file}.
The program accepts the following options. Also see @ref{Common options}.
@table @samp
@item -c @var{k}
@itemx --bytes=@var{k}
@opindex -c
@opindex --bytes
Print the first @var{k} bytes, instead of initial lines.
However, if @var{k} starts with a @samp{-},
print all but the last @var{k} bytes of each file.
@multiplierSuffixes{k}
@itemx -n @var{k}
@itemx --lines=@var{k}
@opindex -n
@opindex --lines
Output the first @var{k} lines.
However, if @var{k} starts with a @samp{-},
print all but the last @var{k} lines of each file.
Size multiplier suffixes are the same as with the @option{-c} option.
@item -q
@itemx --quiet
@itemx --silent
@opindex -q
@opindex --quiet
@opindex --silent
Never print file name headers.
@item -v
@itemx --verbose
@opindex -v
@opindex --verbose
Always print file name headers.
@end table
For compatibility @command{head} also supports an obsolete option syntax
@option{-@var{count}@var{options}}, which is recognized only if it is
specified first. @var{count} is a decimal number optionally followed
by a size letter (@samp{b}, @samp{k}, @samp{m}) as in @option{-c}, or
@samp{l} to mean count by lines, or other option letters (@samp{cqv}).
Scripts intended for standard hosts should use @option{-c @var{count}}
or @option{-n @var{count}} instead. If your script must also run on
hosts that support only the obsolete syntax, it is usually simpler to
avoid @command{head}, e.g., by using @samp{sed 5q} instead of
@samp{head -5}.
@exitstatus
@node tail invocation
@section @command{tail}: Output the last part of files
@pindex tail
@cindex last part of files, outputting
@command{tail} prints the last part (10 lines by default) of each
@var{file}; it reads from standard input if no files are given or
when given a @var{file} of @samp{-}. Synopsis:
@example
tail [@var{option}]@dots{} [@var{file}]@dots{}
@end example
If more than one @var{file} is specified, @command{tail} prints a
one-line header consisting of:
@example
==> @var{file name} <==
@end example
@noindent
before the output for each @var{file}.
@cindex BSD @command{tail}
@sc{gnu} @command{tail} can output any amount of data (some other versions of
@command{tail} cannot). It also has no @option{-r} option (print in
reverse), since reversing a file is really a different job from printing
the end of a file; BSD @command{tail} (which is the one with @option{-r}) can
only reverse files that are at most as large as its buffer, which is
typically 32 KiB@. A more reliable and versatile way to reverse files is
the @sc{gnu} @command{tac} command.
The program accepts the following options. Also see @ref{Common options}.
@table @samp
@item -c @var{k}
@itemx --bytes=@var{k}
@opindex -c
@opindex --bytes
Output the last @var{k} bytes, instead of final lines.
However, if @var{k} starts with a @samp{+}, start printing with the
@var{k}th byte from the start of each file, instead of from the end.
@multiplierSuffixes{k}
@item -f
@itemx --follow[=@var{how}]
@opindex -f
@opindex --follow
@cindex growing files
@vindex name @r{follow option}
@vindex descriptor @r{follow option}
Loop forever trying to read more characters at the end of the file,
presumably because the file is growing.
If more than one file is given, @command{tail} prints a header whenever it
gets output from a different file, to indicate which file that output is
from.
There are two ways to specify how you'd like to track files with this option,
but that difference is noticeable only when a followed file is removed or
renamed.
If you'd like to continue to track the end of a growing file even after
it has been unlinked, use @option{--follow=descriptor}. This is the default
behavior, but it is not useful if you're tracking a log file that may be
rotated (removed or renamed, then reopened). In that case, use
@option{--follow=name} to track the named file, perhaps by reopening it
periodically to see if it has been removed and recreated by some other program.
Note that the inotify-based implementation handles this case without
the need for any periodic reopening.
No matter which method you use, if the tracked file is determined to have
shrunk, @command{tail} prints a message saying the file has been truncated
and resumes tracking the end of the file from the newly-determined endpoint.
When a file is removed, @command{tail}'s behavior depends on whether it is
following the name or the descriptor. When following by name, tail can
detect that a file has been removed and gives a message to that effect,
and if @option{--retry} has been specified it will continue checking
periodically to see if the file reappears.
When following a descriptor, tail does not detect that the file has
been unlinked or renamed and issues no message; even though the file
may no longer be accessible via its original name, it may still be
growing.
The option values @samp{descriptor} and @samp{name} may be specified only
with the long form of the option, not with @option{-f}.
The @option{-f} option is ignored if
no @var{file} operand is specified and standard input is a FIFO or a pipe.
Likewise, the @option{-f} option has no effect for any
operand specified as @samp{-}, when standard input is a FIFO or a pipe.
@item -F
@opindex -F
This option is the same as @option{--follow=name --retry}. That is, tail
will attempt to reopen a file when it is removed. Should this fail, tail
will keep trying until it becomes accessible again.
@itemx --retry
@opindex --retry
This option is useful mainly when following by name (i.e., with
@option{--follow=name}).
Without this option, when tail encounters a file that doesn't
exist or is otherwise inaccessible, it reports that fact and
never checks it again.
@itemx --sleep-interval=@var{number}
@opindex --sleep-interval
Change the number of seconds to wait between iterations (the default is 1.0).
During one iteration, every specified file is checked to see if it has
changed size.
Historical implementations of @command{tail} have required that
@var{number} be an integer. However, GNU @command{tail} accepts
an arbitrary floating point number (using a period before any
fractional digits).
@itemx --pid=@var{pid}
@opindex --pid
When following by name or by descriptor, you may specify the process ID,
@var{pid}, of the sole writer of all @var{file} arguments. Then, shortly
after that process terminates, tail will also terminate. This will
work properly only if the writer and the tailing process are running on
the same machine. For example, to save the output of a build in a file
and to watch the file grow, if you invoke @command{make} and @command{tail}
like this then the tail process will stop when your build completes.
Without this option, you would have had to kill the @code{tail -f}
process yourself.
@example
$ make >& makerr & tail --pid=$! -f makerr
@end example
If you specify a @var{pid} that is not in use or that does not correspond
to the process that is writing to the tailed files, then @command{tail}
may terminate long before any @var{file}s stop growing or it may not
terminate until long after the real writer has terminated.
Note that @option{--pid} cannot be supported on some systems; @command{tail}
will print a warning if this is the case.
@itemx --max-unchanged-stats=@var{n}
@opindex --max-unchanged-stats
When tailing a file by name, if there have been @var{n} (default
n=@value{DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS}) consecutive
iterations for which the file has not changed, then
@code{open}/@code{fstat} the file to determine if that file name is
still associated with the same device/inode-number pair as before.
When following a log file that is rotated, this is approximately the
number of seconds between when tail prints the last pre-rotation lines
and when it prints the lines that have accumulated in the new log file.
This option is meaningful only when following by name.
@itemx -n @var{k}
@itemx --lines=@var{k}
@opindex -n
@opindex --lines
Output the last @var{k} lines.
However, if @var{k} starts with a @samp{+}, start printing with the
@var{k}th line from the start of each file, instead of from the end.
Size multiplier suffixes are the same as with the @option{-c} option.
@item -q
@itemx --quiet
@itemx --silent
@opindex -q
@opindex --quiet
@opindex --silent
Never print file name headers.
@item -v
@itemx --verbose
@opindex -v
@opindex --verbose
Always print file name headers.
@end table
For compatibility @command{tail} also supports an obsolete usage
@samp{tail -[@var{count}][bcl][f] [@var{file}]}, which is recognized
only if it does not conflict with the usage described
above. This obsolete form uses exactly one option and at most one
file. In the option, @var{count} is an optional decimal number optionally
followed by a size letter (@samp{b}, @samp{c}, @samp{l}) to mean count
by 512-byte blocks, bytes, or lines, optionally followed by @samp{f}
which has the same meaning as @option{-f}.
@vindex _POSIX2_VERSION
On older systems, the leading @samp{-} can be replaced by @samp{+} in
the obsolete option syntax with the same meaning as in counts, and
obsolete usage overrides normal usage when the two conflict.
This obsolete behavior can be enabled or disabled with the
@env{_POSIX2_VERSION} environment variable (@pxref{Standards
conformance}).
Scripts intended for use on standard hosts should avoid obsolete
syntax and should use @option{-c @var{count}[b]}, @option{-n
@var{count}}, and/or @option{-f} instead. If your script must also
run on hosts that support only the obsolete syntax, you can often
rewrite it to avoid problematic usages, e.g., by using @samp{sed -n
'$p'} rather than @samp{tail -1}. If that's not possible, the script
can use a test like @samp{if tail -c +1 </dev/null >/dev/null 2>&1;
then @dots{}} to decide which syntax to use.
Even if your script assumes the standard behavior, you should still
beware usages whose behaviors differ depending on the @acronym{POSIX}
version. For example, avoid @samp{tail - main.c}, since it might be
interpreted as either @samp{tail main.c} or as @samp{tail -- -
main.c}; avoid @samp{tail -c 4}, since it might mean either @samp{tail
-c4} or @samp{tail -c 10 4}; and avoid @samp{tail +4}, since it might
mean either @samp{tail ./+4} or @samp{tail -n +4}.
@exitstatus
@node split invocation
@section @command{split}: Split a file into fixed-size pieces
@pindex split
@cindex splitting a file into pieces
@cindex pieces, splitting a file into
@command{split} creates output files containing consecutive sections of
@var{input} (standard input if none is given or @var{input} is
@samp{-}). Synopsis:
@example
split [@var{option}] [@var{input} [@var{prefix}]]
@end example
By default, @command{split} puts 1000 lines of @var{input} (or whatever is
left over for the last section), into each output file.
@cindex output file name prefix
The output files' names consist of @var{prefix} (@samp{x} by default)
followed by a group of characters (@samp{aa}, @samp{ab}, @dots{} by
default), such that concatenating the output files in traditional
sorted order by file name produces
the original input file. If the output file names are exhausted,
@command{split} reports an error without deleting the output files
that it did create.
The program accepts the following options. Also see @ref{Common options}.
@table @samp
@item -l @var{lines}
@itemx --lines=@var{lines}
@opindex -l
@opindex --lines
Put @var{lines} lines of @var{input} into each output file.
For compatibility @command{split} also supports an obsolete
option syntax @option{-@var{lines}}. New scripts should use @option{-l
@var{lines}} instead.
@item -b @var{size}
@itemx --bytes=@var{size}
@opindex -b
@opindex --bytes
Put @var{size} bytes of @var{input} into each output file.
@multiplierSuffixes{size}
@item -C @var{size}
@itemx --line-bytes=@var{size}
@opindex -C
@opindex --line-bytes
Put into each output file as many complete lines of @var{input} as
possible without exceeding @var{size} bytes. Individual lines longer than
@var{size} bytes are broken into multiple files.
@var{size} has the same format as for the @option{--bytes} option.
@item -a @var{length}
@itemx --suffix-length=@var{length}
@opindex -a
@opindex --suffix-length
Use suffixes of length @var{length}. The default @var{length} is 2.
@item -d
@itemx --numeric-suffixes
@opindex -d
@opindex --numeric-suffixes
Use digits in suffixes rather than lower-case letters.
@itemx --verbose
@opindex --verbose
Write a diagnostic just before each output file is opened.
@end table
@exitstatus
@node csplit invocation
@section @command{csplit}: Split a file into context-determined pieces
@pindex csplit
@cindex context splitting
@cindex splitting a file into pieces by context
@command{csplit} creates zero or more output files containing sections of
@var{input} (standard input if @var{input} is @samp{-}). Synopsis:
@example
csplit [@var{option}]@dots{} @var{input} @var{pattern}@dots{}
@end example
The contents of the output files are determined by the @var{pattern}
arguments, as detailed below. An error occurs if a @var{pattern}
argument refers to a nonexistent line of the input file (e.g., if no
remaining line matches a given regular expression). After every
@var{pattern} has been matched, any remaining input is copied into one
last output file.
By default, @command{csplit} prints the number of bytes written to each
output file after it has been created.
The types of pattern arguments are:
@table @samp
@item @var{n}
Create an output file containing the input up to but not including line
@var{n} (a positive integer). If followed by a repeat count, also
create an output file containing the next @var{n} lines of the input
file once for each repeat.
@item /@var{regexp}/[@var{offset}]
Create an output file containing the current line up to (but not
including) the next line of the input file that contains a match for
@var{regexp}. The optional @var{offset} is an integer.
If it is given, the input up to (but not including) the
matching line plus or minus @var{offset} is put into the output file,
and the line after that begins the next section of input.
@item %@var{regexp}%[@var{offset}]
Like the previous type, except that it does not create an output
file, so that section of the input file is effectively ignored.
@item @{@var{repeat-count}@}
Repeat the previous pattern @var{repeat-count} additional
times. The @var{repeat-count} can either be a positive integer or an
asterisk, meaning repeat as many times as necessary until the input is
exhausted.
@end table
The output files' names consist of a prefix (@samp{xx} by default)
followed by a suffix. By default, the suffix is an ascending sequence
of two-digit decimal numbers from @samp{00} to @samp{99}. In any case,
concatenating the output files in sorted order by file name produces the
original input file.
By default, if @command{csplit} encounters an error or receives a hangup,
interrupt, quit, or terminate signal, it removes any output files
that it has created so far before it exits.
The program accepts the following options. Also see @ref{Common options}.
@table @samp
@item -f @var{prefix}
@itemx --prefix=@var{prefix}
@opindex -f
@opindex --prefix
@cindex output file name prefix
Use @var{prefix} as the output file name prefix.
@item -b @var{suffix}
@itemx --suffix=@var{suffix}
@opindex -b
@opindex --suffix
@cindex output file name suffix
Use @var{suffix} as the output file name suffix. When this option is
specified, the suffix string must include exactly one
@code{printf(3)}-style conversion specification, possibly including
format specification flags, a field width, a precision specifications,
or all of these kinds of modifiers. The format letter must convert a
binary unsigned integer argument to readable form. The format letters
@samp{d} and @samp{i} are aliases for @samp{u}, and the
@samp{u}, @samp{o}, @samp{x}, and @samp{X} conversions are allowed. The
entire @var{suffix} is given (with the current output file number) to
@code{sprintf(3)} to form the file name suffixes for each of the
individual output files in turn. If this option is used, the
@option{--digits} option is ignored.
@item -n @var{digits}
@itemx --digits=@var{digits}
@opindex -n
@opindex --digits
Use output file names containing numbers that are @var{digits} digits
long instead of the default 2.
@item -k
@itemx --keep-files
@opindex -k
@opindex --keep-files
Do not remove output files when errors are encountered.
@item -z
@itemx --elide-empty-files
@opindex -z
@opindex --elide-empty-files
Suppress the generation of zero-length output files. (In cases where
the section delimiters of the input file are supposed to mark the first
lines of each of the sections, the first output file will generally be a
zero-length file unless you use this option.) The output file sequence
numbers always run consecutively starting from 0, even when this option
is specified.
@item -s
@itemx -q
@itemx --silent
@itemx --quiet
@opindex -s
@opindex -q
@opindex --silent
@opindex --quiet
Do not print counts of output file sizes.
@end table
@exitstatus
Here is an example of its usage.
First, create an empty directory for the exercise,
and cd into it:
@example
$ mkdir d && cd d
@end example
Now, split the sequence of 1..14 on lines that end with 0 or 5:
@example
$ seq 14 | csplit - '/[05]$/' '@{*@}'
8
10
15
@end example
Each number printed above is the size of an output
file that csplit has just created.
List the names of those output files:
@example
$ ls
xx00 xx01 xx02
@end example
Use @command{head} to show their contents:
@example
$ head xx*
==> xx00 <==
1
2
3
4
==> xx01 <==
5
6
7
8
9
==> xx02 <==
10
11
12
13
14
@end example
@node Summarizing files
@chapter Summarizing files
@cindex summarizing files
These commands generate just a few numbers representing entire
contents of files.
@menu
* wc invocation:: Print newline, word, and byte counts.
* sum invocation:: Print checksum and block counts.
* cksum invocation:: Print CRC checksum and byte counts.
* md5sum invocation:: Print or check MD5 digests.
* sha1sum invocation:: Print or check SHA-1 digests.
* sha2 utilities:: Print or check SHA-2 digests.
@end menu
@node wc invocation
@section @command{wc}: Print newline, word, and byte counts
@pindex wc
@cindex byte count
@cindex character count
@cindex word count
@cindex line count
@command{wc} counts the number of bytes, characters, whitespace-separated
words, and newlines in each given @var{file}, or standard input if none
are given or for a @var{file} of @samp{-}. Synopsis:
@example
wc [@var{option}]@dots{} [@var{file}]@dots{}
@end example
@cindex total counts
@command{wc} prints one line of counts for each file, and if the file was
given as an argument, it prints the file name following the counts. If
more than one @var{file} is given, @command{wc} prints a final line
containing the cumulative counts, with the file name @file{total}. The
counts are printed in this order: newlines, words, characters, bytes,
maximum line length.
Each count is printed right-justified in a field with at least one
space between fields so that the numbers and file names normally line
up nicely in columns. The width of the count fields varies depending
on the inputs, so you should not depend on a particular field width.
However, as a @acronym{GNU} extension, if only one count is printed,
it is guaranteed to be printed without leading spaces.
By default, @command{wc} prints three counts: the newline, words, and byte
counts. Options can specify that only certain counts be printed.
Options do not undo others previously given, so
@example
wc --bytes --words
@end example
@noindent
prints both the byte counts and the word counts.
With the @option{--max-line-length} option, @command{wc} prints the length
of the longest line per file, and if there is more than one file it
prints the maximum (not the sum) of those lengths. The line lengths here
are measured in screen columns, according to the current locale and
assuming tab positions in every 8th column.
The program accepts the following options. Also see @ref{Common options}.
@table @samp
@item -c
@itemx --bytes
@opindex -c
@opindex --bytes
Print only the byte counts.
@item -m
@itemx --chars
@opindex -m
@opindex --chars
Print only the character counts.
@item -w
@itemx --words
@opindex -w
@opindex --words
Print only the word counts.
@item -l
@itemx --lines
@opindex -l
@opindex --lines
Print only the newline counts.
@item -L
@itemx --max-line-length
@opindex -L
@opindex --max-line-length
Print only the maximum line lengths.
@macro filesZeroFromOption{cmd,withTotalOption,subListOutput}
@itemx --files0-from=@var{file}
@opindex --files0-from=@var{file}
@c This is commented out to avoid a texi2dvi failure.
@c texi2dvi (GNU Texinfo 4.11) 1.104
@c @cindex including files from @command{\cmd\}
Disallow processing files named on the command line, and instead process
those named in file @var{file}; each name being terminated by a zero byte
(@acronym{ASCII} @sc{nul}).
This is useful \withTotalOption\
when the list of file names is so long that it may exceed a command line
length limitation.
In such cases, running @command{\cmd\} via @command{xargs} is undesirable
because it splits the list into pieces and makes @command{\cmd\} print
\subListOutput\ for each sublist rather than for the entire list.
One way to produce a list of @acronym{ASCII} @sc{nul} terminated file names is with @sc{gnu}
@command{find}, using its @option{-print0} predicate.
If @var{file} is @samp{-} then the @acronym{ASCII} @sc{nul} terminated file names
are read from standard input.
@end macro
@filesZeroFromOption{wc,,a total}
For example, to find the length of the longest line in any @file{.c} or
@file{.h} file in the current hierarchy, do this:
@example
find . -name '*.[ch]' -print0 |
wc -L --files0-from=- | tail -n1
@end example
@end table
@exitstatus
@node sum invocation
@section @command{sum}: Print checksum and block counts
@pindex sum
@cindex 16-bit checksum
@cindex checksum, 16-bit
@command{sum} computes a 16-bit checksum for each given @var{file}, or
standard input if none are given or for a @var{file} of @samp{-}. Synopsis:
@example
sum [@var{option}]@dots{} [@var{file}]@dots{}
@end example
@command{sum} prints the checksum for each @var{file} followed by the
number of blocks in the file (rounded up). If more than one @var{file}
is given, file names are also printed (by default). (With the
@option{--sysv} option, corresponding file names are printed when there is
at least one file argument.)
By default, @sc{gnu} @command{sum} computes checksums using an algorithm
compatible with BSD @command{sum} and prints file sizes in units of
1024-byte blocks.
The program accepts the following options. Also see @ref{Common options}.
@table @samp
@item -r
@opindex -r
@cindex BSD @command{sum}
Use the default (BSD compatible) algorithm. This option is included for
compatibility with the System V @command{sum}. Unless @option{-s} was also
given, it has no effect.
@item -s
@itemx --sysv
@opindex -s
@opindex --sysv
@cindex System V @command{sum}
Compute checksums using an algorithm compatible with System V
@command{sum}'s default, and print file sizes in units of 512-byte blocks.
@end table
@command{sum} is provided for compatibility; the @command{cksum} program (see
next section) is preferable in new applications.
@exitstatus
@node cksum invocation
@section @command{cksum}: Print CRC checksum and byte counts
@pindex cksum
@cindex cyclic redundancy check
@cindex CRC checksum
@command{cksum} computes a cyclic redundancy check (CRC) checksum for each
given @var{file}, or standard input if none are given or for a
@var{file} of @samp{-}. Synopsis:
@example
cksum [@var{option}]@dots{} [@var{file}]@dots{}
@end example
@command{cksum} prints the CRC checksum for each file along with the number
of bytes in the file, and the file name unless no arguments were given.
@command{cksum} is typically used to ensure that files
transferred by unreliable means (e.g., netnews) have not been corrupted,
by comparing the @command{cksum} output for the received files with the
@command{cksum} output for the original files (typically given in the
distribution).
The CRC algorithm is specified by the @acronym{POSIX} standard. It is not
compatible with the BSD or System V @command{sum} algorithms (see the
previous section); it is more robust.
The only options are @option{--help} and @option{--version}. @xref{Common
options}.
@exitstatus
@node md5sum invocation
@section @command{md5sum}: Print or check MD5 digests
@pindex md5sum
@cindex MD5
@cindex 128-bit checksum
@cindex checksum, 128-bit
@cindex fingerprint, 128-bit
@cindex message-digest, 128-bit
@command{md5sum} computes a 128-bit checksum (or @dfn{fingerprint} or
@dfn{message-digest}) for each specified @var{file}.
Note: The MD5 digest is more reliable than a simple CRC (provided by
the @command{cksum} command) for detecting accidental file corruption,
as the chances of accidentally having two files with identical MD5
are vanishingly small. However, it should not be considered secure
against malicious tampering: although finding a file with a given MD5
fingerprint is considered infeasible at the moment, it is known how
to modify certain files, including digital certificates, so that they
appear valid when signed with an MD5 digest.
For more secure hashes, consider using SHA-2. @xref{sha2 utilities}.
If a @var{file} is specified as @samp{-} or if no files are given
@command{md5sum} computes the checksum for the standard input.
@command{md5sum} can also determine whether a file and checksum are
consistent. Synopsis:
@example
md5sum [@var{option}]@dots{} [@var{file}]@dots{}
@end example
For each @var{file}, @samp{md5sum} outputs the MD5 checksum, a flag
indicating a binary or text input file, and the file name.
If @var{file} contains a backslash or newline, the
line is started with a backslash, and each problematic character in
the file name is escaped with a backslash, making the output
unambiguous even in the presence of arbitrary file names.
If @var{file} is omitted or specified as @samp{-}, standard input is read.
The program accepts the following options. Also see @ref{Common options}.
@table @samp
@item -b
@itemx --binary
@opindex -b
@opindex --binary
@cindex binary input files
Treat each input file as binary, by reading it in binary mode and
outputting a @samp{*} flag. This is the inverse of @option{--text}.
On systems like @acronym{GNU} that do not distinguish between binary
and text files, this option merely flags each input file as binary:
the MD5 checksum is unaffected. This option is the default on systems
like MS-DOS that distinguish between binary and text files, except
for reading standard input when standard input is a terminal.
@item -c
@itemx --check
Read file names and checksum information (not data) from each
@var{file} (or from stdin if no @var{file} was specified) and report
whether the checksums match the contents of the named files.
The input to this mode of @command{md5sum} is usually the output of
a prior, checksum-generating run of @samp{md5sum}.
Each valid line of input consists of an MD5 checksum, a binary/text
flag, and then a file name.
Binary files are marked with @samp{*}, text with @samp{ }.
For each such line, @command{md5sum} reads the named file and computes its
MD5 checksum. Then, if the computed message digest does not match the
one on the line with the file name, the file is noted as having
failed the test. Otherwise, the file passes the test.
By default, for each valid line, one line is written to standard
output indicating whether the named file passed the test.
After all checks have been performed, if there were any failures,
a warning is issued to standard error.
Use the @option{--status} option to inhibit that output.
If any listed file cannot be opened or read, if any valid line has
an MD5 checksum inconsistent with the associated file, or if no valid
line is found, @command{md5sum} exits with nonzero status. Otherwise,
it exits successfully.
@itemx --quiet
@opindex --quiet
@cindex verifying MD5 checksums
This option is useful only when verifying checksums.
When verifying checksums, don't generate an 'OK' message per successfully
checked file. Files that fail the verification are reported in the
default one-line-per-file format. If there is any checksum mismatch,
print a warning summarizing the failures to standard error.
@itemx --status
@opindex --status
@cindex verifying MD5 checksums
This option is useful only when verifying checksums.
When verifying checksums, don't generate the default one-line-per-file
diagnostic and don't output the warning summarizing any failures.
Failures to open or read a file still evoke individual diagnostics to
standard error.
If all listed files are readable and are consistent with the associated
MD5 checksums, exit successfully. Otherwise exit with a status code
indicating there was a failure.
@item -t
@itemx --text
@opindex -t
@opindex --text
@cindex text input files
Treat each input file as text, by reading it in text mode and
outputting a @samp{ } flag. This is the inverse of @option{--binary}.
This option is the default on systems like @acronym{GNU} that do not
distinguish between binary and text files. On other systems, it is
the default for reading standard input when standard input is a
terminal.
@item -w
@itemx --warn
@opindex -w
@opindex --warn
@cindex verifying MD5 checksums
When verifying checksums, warn about improperly formatted MD5 checksum lines.
This option is useful only if all but a few lines in the checked input
are valid.
@end table
@exitstatus
@node sha1sum invocation
@section @command{sha1sum}: Print or check SHA-1 digests
@pindex sha1sum
@cindex SHA-1
@cindex 160-bit checksum
@cindex checksum, 160-bit
@cindex fingerprint, 160-bit
@cindex message-digest, 160-bit
@command{sha1sum} computes a 160-bit checksum for each specified
@var{file}. The usage and options of this command are precisely the
same as for @command{md5sum}. @xref{md5sum invocation}.
Note: The SHA-1 digest is more secure than MD5, and no collisions of
it are known (different files having the same fingerprint). However,
it is known that they can be produced with considerable, but not
unreasonable, resources. For this reason, it is generally considered
that SHA-1 should be gradually phased out in favor of the more secure
SHA-2 hash algorithms. @xref{sha2 utilities}.
@node sha2 utilities
@section sha2 utilities: Print or check SHA-2 digests
@pindex sha224sum
@pindex sha256sum
@pindex sha384sum
@pindex sha512sum
@cindex SHA-2
@cindex 224-bit checksum
@cindex 256-bit checksum
@cindex 384-bit checksum
@cindex 512-bit checksum
@cindex checksum, 224-bit
@cindex checksum, 256-bit
@cindex checksum, 384-bit
@cindex checksum, 512-bit
@cindex fingerprint, 224-bit
@cindex fingerprint, 256-bit
@cindex fingerprint, 384-bit
@cindex fingerprint, 512-bit
@cindex message-digest, 224-bit
@cindex message-digest, 256-bit
@cindex message-digest, 384-bit
@cindex message-digest, 512-bit
The commands @command{sha224sum}, @command{sha256sum},
@command{sha384sum} and @command{sha512sum} compute checksums of
various lengths (respectively 224, 256, 384 and 512 bits),
collectively known as the SHA-2 hashes. The usage and options of
these commands are precisely the same as for @command{md5sum}.
@xref{md5sum invocation}.
Note: The SHA384 and SHA512 digests are considerably slower to
compute, especially on 32-bit computers, than SHA224 or SHA256.
@node Operating on sorted files
@chapter Operating on sorted files
@cindex operating on sorted files
@cindex sorted files, operations on
These commands work with (or produce) sorted files.
@menu
* sort invocation:: Sort text files.
* shuf invocation:: Shuffle text files.
* uniq invocation:: Uniquify files.
* comm invocation:: Compare two sorted files line by line.
* ptx invocation:: Produce a permuted index of file contents.
* tsort invocation:: Topological sort.
@end menu
@node sort invocation
@section @command{sort}: Sort text files
@pindex sort
@cindex sorting files
@command{sort} sorts, merges, or compares all the lines from the given
files, or standard input if none are given or for a @var{file} of
@samp{-}. By default, @command{sort} writes the results to standard
output. Synopsis:
@example
sort [@var{option}]@dots{} [@var{file}]@dots{}
@end example
@command{sort} has three modes of operation: sort (the default), merge,
and check for sortedness. The following options change the operation
mode:
@table @samp
@item -c
@itemx --check
@itemx --check=diagnose-first
@opindex -c
@opindex --check
@cindex checking for sortedness
Check whether the given file is already sorted: if it is not all
sorted, print a diagnostic containing the first out-of-order line and
exit with a status of 1.
Otherwise, exit successfully.
At most one input file can be given.
@item -C
@itemx --check=quiet
@itemx --check=silent
@opindex -c
@opindex --check
@cindex checking for sortedness
Exit successfully if the given file is already sorted, and
exit with status 1 otherwise.
At most one input file can be given.
This is like @option{-c}, except it does not print a diagnostic.
@item -m
@itemx --merge
@opindex -m
@opindex --merge
@cindex merging sorted files
Merge the given files by sorting them as a group. Each input file must
always be individually sorted. It always works to sort instead of
merge; merging is provided because it is faster, in the case where it
works.
@end table
@cindex sort stability
@cindex sort's last-resort comparison
A pair of lines is compared as follows:
@command{sort} compares each pair of fields, in the
order specified on the command line, according to the associated
ordering options, until a difference is found or no fields are left.
If no key fields are specified, @command{sort} uses a default key of
the entire line. Finally, as a last resort when all keys compare
equal, @command{sort} compares entire lines as if no ordering options
other than @option{--reverse} (@option{-r}) were specified. The
@option{--stable} (@option{-s}) option disables this @dfn{last-resort
comparison} so that lines in which all fields compare equal are left
in their original relative order. The @option{--unique}
(@option{-u}) option also disables the last-resort comparison.
@vindex LC_ALL
@vindex LC_COLLATE
Unless otherwise specified, all comparisons use the character collating
sequence specified by the @env{LC_COLLATE} locale.@footnote{If you
use a non-@acronym{POSIX} locale (e.g., by setting @env{LC_ALL}
to @samp{en_US}), then @command{sort} may produce output that is sorted
differently than you're accustomed to. In that case, set the @env{LC_ALL}
environment variable to @samp{C}. Note that setting only @env{LC_COLLATE}
has two problems. First, it is ineffective if @env{LC_ALL} is also set.
Second, it has undefined behavior if @env{LC_CTYPE} (or @env{LANG}, if
@env{LC_CTYPE} is unset) is set to an incompatible value. For example,
you get undefined behavior if @env{LC_CTYPE} is @code{ja_JP.PCK} but
@env{LC_COLLATE} is @code{en_US.UTF-8}.}
@sc{gnu} @command{sort} (as specified for all @sc{gnu} utilities) has no
limit on input line length or restrictions on bytes allowed within lines.
In addition, if the final byte of an input file is not a newline, @sc{gnu}
@command{sort} silently supplies one. A line's trailing newline is not
part of the line for comparison purposes.
@cindex exit status of @command{sort}
Exit status:
@display
0 if no error occurred
1 if invoked with @option{-c} or @option{-C} and the input is not sorted
2 if an error occurred
@end display
@vindex TMPDIR
If the environment variable @env{TMPDIR} is set, @command{sort} uses its
value as the directory for temporary files instead of @file{/tmp}. The
@option{--temporary-directory} (@option{-T}) option in turn overrides
the environment variable.
The following options affect the ordering of output lines. They may be
specified globally or as part of a specific key field. If no key
fields are specified, global options apply to comparison of entire
lines; otherwise the global options are inherited by key fields that do
not specify any special options of their own. In pre-@acronym{POSIX}
versions of @command{sort}, global options affect only later key fields,
so portable shell scripts should specify global options first.
@table @samp
@item -b
@itemx --ignore-leading-blanks
@opindex -b
@opindex --ignore-leading-blanks
@cindex blanks, ignoring leading
@vindex LC_CTYPE
Ignore leading blanks when finding sort keys in each line.
By default a blank is a space or a tab, but the @env{LC_CTYPE} locale
can change this. Note blanks may be ignored by your locale's collating
rules, but without this option they will be significant for character
positions specified in keys with the @option{-k} option.
@item -d
@itemx --dictionary-order
@opindex -d
@opindex --dictionary-order
@cindex dictionary order
@cindex phone directory order
@cindex telephone directory order
@vindex LC_CTYPE
Sort in @dfn{phone directory} order: ignore all characters except
letters, digits and blanks when sorting.
By default letters and digits are those of @acronym{ASCII} and a blank
is a space or a tab, but the @env{LC_CTYPE} locale can change this.
@item -f
@itemx --ignore-case
@opindex -f
@opindex --ignore-case
@cindex ignoring case
@cindex case folding
@vindex LC_CTYPE
Fold lowercase characters into the equivalent uppercase characters when
comparing so that, for example, @samp{b} and @samp{B} sort as equal.
The @env{LC_CTYPE} locale determines character types.
When used with @option{--unique} those lower case equivalent lines are
thrown away. (There is currently no way to throw away the upper case
equivalent instead. (Any @option{--reverse} given would only affect
the final result, after the throwing away.))
@item -g
@itemx --general-numeric-sort
@itemx --sort=general-numeric
@opindex -g
@opindex --general-numeric-sort
@opindex --sort
@cindex general numeric sort
@vindex LC_NUMERIC
Sort numerically, using the standard C function @code{strtold} to convert
a prefix of each line to a long double-precision floating point number.
This allows floating point numbers to be specified in scientific notation,
like @code{1.0e-34} and @code{10e100}.
The @env{LC_NUMERIC} locale determines the decimal-point character.
Do not report overflow, underflow, or conversion errors.
Use the following collating sequence:
@itemize @bullet
@item
Lines that do not start with numbers (all considered to be equal).
@item
NaNs (``Not a Number'' values, in IEEE floating point arithmetic)
in a consistent but machine-dependent order.
@item
Minus infinity.
@item
Finite numbers in ascending numeric order (with @math{-0} and @math{+0} equal).
@item
Plus infinity.
@end itemize
Use this option only if there is no alternative; it is much slower than
@option{--numeric-sort} (@option{-n}) and it can lose information when
converting to floating point.
@item -h
@itemx --human-numeric-sort
@itemx --sort=human-numeric
@opindex -h
@opindex --human-numeric-sort
@opindex --sort
@cindex human numeric sort
@vindex LC_NUMERIC
Sort numerically, first by numeric sign (negative, zero, or positive);
then by @acronym{SI} suffix (either empty, or @samp{k} or @samp{K}, or
one of @samp{MGTPEZY}, in that order; @pxref{Block size}); and finally
by numeric value. For example, @samp{1023M} sorts before @samp{1G}
because @samp{M} (mega) precedes @samp{G} (giga) as an @acronym{SI}
suffix. This option sorts values that are consistently scaled to the
nearest suffix, regardless of whether suffixes denote powers of 1000
or 1024, and it therefore sorts the output of any single invocation of
the @command{df}, @command{du}, or @command{ls} commands that are
invoked with their @option{--human-readable} or @option{--si} options.
The syntax for numbers is the same as for the @option{--numeric-sort}
option; the @acronym{SI} suffix must immediately follow the number.
@item -i
@itemx --ignore-nonprinting
@opindex -i
@opindex --ignore-nonprinting
@cindex nonprinting characters, ignoring
@cindex unprintable characters, ignoring
@vindex LC_CTYPE
Ignore nonprinting characters.
The @env{LC_CTYPE} locale determines character types.
This option has no effect if the stronger @option{--dictionary-order}
(@option{-d}) option is also given.
@item -M
@itemx --month-sort
@itemx --sort=month
@opindex -M
@opindex --month-sort
@opindex --sort
@cindex months, sorting by
@vindex LC_TIME
An initial string, consisting of any amount of blanks, followed
by a month name abbreviation, is folded to UPPER case and
compared in the order @samp{JAN} < @samp{FEB} < @dots{} < @samp{DEC}.
Invalid names compare low to valid names. The @env{LC_TIME} locale
category determines the month spellings.
By default a blank is a space or a tab, but the @env{LC_CTYPE} locale
can change this.
@item -n
@itemx --numeric-sort
@itemx --sort=numeric
@opindex -n
@opindex --numeric-sort
@opindex --sort
@cindex numeric sort
@vindex LC_NUMERIC
Sort numerically. The number begins each line and consists
of optional blanks, an optional @samp{-} sign, and zero or more
digits possibly separated by thousands separators, optionally followed
by a decimal-point character and zero or more digits. An empty
number is treated as @samp{0}. The @env{LC_NUMERIC}
locale specifies the decimal-point character and thousands separator.
By default a blank is a space or a tab, but the @env{LC_CTYPE} locale
can change this.
Comparison is exact; there is no rounding error.
Neither a leading @samp{+} nor exponential notation is recognized.
To compare such strings numerically, use the
@option{--general-numeric-sort} (@option{-g}) option.
@item -V
@itemx --version-sort
@opindex -V
@opindex --version-sort
@cindex version number sort
Sort by version name and number. It behaves like a standard sort,
except that each sequence of decimal digits is treated numerically
as an index/version number. (@xref{Details about version sort}.)
@item -r
@itemx --reverse
@opindex -r
@opindex --reverse
@cindex reverse sorting
Reverse the result of comparison, so that lines with greater key values
appear earlier in the output instead of later.
@item -R
@itemx --random-sort
@itemx --sort=random
@opindex -R
@opindex --random-sort
@opindex --sort
@cindex random sort
Sort by hashing the input keys and then sorting the hash values.
Choose the hash function at random, ensuring that it is free of
collisions so that differing keys have differing hash values. This is
like a random permutation of the inputs (@pxref{shuf invocation}),
except that keys with the same value sort together.
If multiple random sort fields are specified, the same random hash
function is used for all fields. To use different random hash
functions for different fields, you can invoke @command{sort} more
than once.
The choice of hash function is affected by the
@option{--random-source} option.
@end table
Other options are:
@table @samp
@item --compress-program=@var{prog}
Compress any temporary files with the program @var{prog}.
With no arguments, @var{prog} must compress standard input to standard
output, and when given the @option{-d} option it must decompress
standard input to standard output.
Terminate with an error if @var{prog} exits with nonzero status.
White space and the backslash character should not appear in
@var{prog}; they are reserved for future use.
@filesZeroFromOption{sort,,sorted output}
@item -k @var{pos1}[,@var{pos2}]
@itemx --key=@var{pos1}[,@var{pos2}]
@opindex -k
@opindex --key
@cindex sort field
Specify a sort field that consists of the part of the line between
@var{pos1} and @var{pos2} (or the end of the line, if @var{pos2} is
omitted), @emph{inclusive}.
Each @var{pos} has the form @samp{@var{f}[.@var{c}][@var{opts}]},
where @var{f} is the number of the field to use, and @var{c} is the number
of the first character from the beginning of the field. Fields and character
positions are numbered starting with 1; a character position of zero in
@var{pos2} indicates the field's last character. If @samp{.@var{c}} is
omitted from @var{pos1}, it defaults to 1 (the beginning of the field);
if omitted from @var{pos2}, it defaults to 0 (the end of the field).
@var{opts} are ordering options, allowing individual keys to be sorted
according to different rules; see below for details. Keys can span
multiple fields.
Example: To sort on the second field, use @option{--key=2,2}
(@option{-k 2,2}). See below for more notes on keys and more examples.
See also the @option{--debug} option to help determine the part
of the line being used in the sort.
@item --debug
Highlight the portion of each line used for sorting.
Also issue warnings about questionable usage to stderr.
@item --batch-size=@var{nmerge}
@opindex --batch-size
@cindex number of inputs to merge, nmerge
Merge at most @var{nmerge} inputs at once.
When @command{sort} has to merge more than @var{nmerge} inputs,
it merges them in groups of @var{nmerge}, saving the result in
a temporary file, which is then used as an input in a subsequent merge.
A large value of @var{nmerge} may improve merge performance and decrease
temporary storage utilization at the expense of increased memory usage
and I/0. Conversely a small value of @var{nmerge} may reduce memory
requirements and I/0 at the expense of temporary storage consumption and
merge performance.
The value of @var{nmerge} must be at least 2. The default value is
currently 16, but this is implementation-dependent and may change in
the future.
The value of @var{nmerge} may be bounded by a resource limit for open
file descriptors. The commands @samp{ulimit -n} or @samp{getconf
OPEN_MAX} may display limits for your systems; these limits may be
modified further if your program already has some files open, or if
the operating system has other limits on the number of open files. If
the value of @var{nmerge} exceeds the resource limit, @command{sort}
silently uses a smaller value.
@item -o @var{output-file}
@itemx --output=@var{output-file}
@opindex -o
@opindex --output
@cindex overwriting of input, allowed
Write output to @var{output-file} instead of standard output.
Normally, @command{sort} reads all input before opening
@var{output-file}, so you can safely sort a file in place by using
commands like @code{sort -o F F} and @code{cat F | sort -o F}.
However, @command{sort} with @option{--merge} (@option{-m}) can open
the output file before reading all input, so a command like @code{cat
F | sort -m -o F - G} is not safe as @command{sort} might start
writing @file{F} before @command{cat} is done reading it.
@vindex POSIXLY_CORRECT
On newer systems, @option{-o} cannot appear after an input file if
@env{POSIXLY_CORRECT} is set, e.g., @samp{sort F -o F}. Portable
scripts should specify @option{-o @var{output-file}} before any input
files.
@item --random-source=@var{file}
@opindex --random-source
@cindex random source for sorting
Use @var{file} as a source of random data used to determine which
random hash function to use with the @option{-R} option. @xref{Random
sources}.
@item -s
@itemx --stable
@opindex -s
@opindex --stable
@cindex sort stability
@cindex sort's last-resort comparison
Make @command{sort} stable by disabling its last-resort comparison.
This option has no effect if no fields or global ordering options
other than @option{--reverse} (@option{-r}) are specified.
@item -S @var{size}
@itemx --buffer-size=@var{size}
@opindex -S
@opindex --buffer-size
@cindex size for main memory sorting
Use a main-memory sort buffer of the given @var{size}. By default,
@var{size} is in units of 1024 bytes. Appending @samp{%} causes
@var{size} to be interpreted as a percentage of physical memory.
Appending @samp{K} multiplies @var{size} by 1024 (the default),
@samp{M} by 1,048,576, @samp{G} by 1,073,741,824, and so on for
@samp{T}, @samp{P}, @samp{E}, @samp{Z}, and @samp{Y}. Appending
@samp{b} causes @var{size} to be interpreted as a byte count, with no
multiplication.
This option can improve the performance of @command{sort} by causing it
to start with a larger or smaller sort buffer than the default.
However, this option affects only the initial buffer size. The buffer
grows beyond @var{size} if @command{sort} encounters input lines larger
than @var{size}.
@item -t @var{separator}
@itemx --field-separator=@var{separator}
@opindex -t
@opindex --field-separator
@cindex field separator character
Use character @var{separator} as the field separator when finding the
sort keys in each line. By default, fields are separated by the empty
string between a non-blank character and a blank character.
By default a blank is a space or a tab, but the @env{LC_CTYPE} locale
can change this.
That is, given the input line @w{@samp{ foo bar}}, @command{sort} breaks it
into fields @w{@samp{ foo}} and @w{@samp{ bar}}. The field separator is
not considered to be part of either the field preceding or the field
following, so with @samp{sort @w{-t " "}} the same input line has
three fields: an empty field, @samp{foo}, and @samp{bar}.
However, fields that extend to the end of the line,
as @option{-k 2}, or fields consisting of a range, as @option{-k 2,3},
retain the field separators present between the endpoints of the range.
To specify @acronym{ASCII} @sc{nul} as the field separator,
use the two-character string @samp{\0}, e.g., @samp{sort -t '\0'}.
@item -T @var{tempdir}
@itemx --temporary-directory=@var{tempdir}
@opindex -T
@opindex --temporary-directory
@cindex temporary directory
@vindex TMPDIR
Use directory @var{tempdir} to store temporary files, overriding the
@env{TMPDIR} environment variable. If this option is given more than
once, temporary files are stored in all the directories given. If you
have a large sort or merge that is I/O-bound, you can often improve
performance by using this option to specify directories on different
disks and controllers.
@item --parallel=@var{n}
@opindex --parallel
@cindex multithreaded sort
Limit the number of sorts run in parallel to @var{n}. By default,
@var{n} is set to the number of available processors, and values
greater than that are reduced to that limit. Also see
@ref{nproc invocation}.
@item -u
@itemx --unique
@opindex -u
@opindex --unique
@cindex uniquifying output
Normally, output only the first of a sequence of lines that compare
equal. For the @option{--check} (@option{-c} or @option{-C}) option,
check that no pair of consecutive lines compares equal.
This option also disables the default last-resort comparison.
The commands @code{sort -u} and @code{sort | uniq} are equivalent, but
this equivalence does not extend to arbitrary @command{sort} options.
For example, @code{sort -n -u} inspects only the value of the initial
numeric string when checking for uniqueness, whereas @code{sort -n |
uniq} inspects the entire line. @xref{uniq invocation}.
@macro zeroTerminatedOption
@item -z
@itemx --zero-terminated
@opindex -z
@opindex --zero-terminated
@cindex process zero-terminated items
Delimit items with a zero byte rather than a newline (@acronym{ASCII} @sc{lf}).
I.E. treat input as items separated by @acronym{ASCII} @sc{nul}
and terminate output items with @acronym{ASCII} @sc{nul}.
This option can be useful in conjunction with @samp{perl -0} or
@samp{find -print0} and @samp{xargs -0} which do the same in order to
reliably handle arbitrary file names (even those containing blanks
or other special characters).
@end macro
@zeroTerminatedOption
@end table
Historical (BSD and System V) implementations of @command{sort} have
differed in their interpretation of some options, particularly
@option{-b}, @option{-f}, and @option{-n}. @sc{gnu} sort follows the @acronym{POSIX}
behavior, which is usually (but not always!) like the System V behavior.
According to @acronym{POSIX}, @option{-n} no longer implies @option{-b}. For
consistency, @option{-M} has been changed in the same way. This may
affect the meaning of character positions in field specifications in
obscure cases. The only fix is to add an explicit @option{-b}.
A position in a sort field specified with @option{-k} may have any
of the option letters @samp{MbdfghinRrV} appended to it, in which case no
global ordering options are inherited by that particular field. The
@option{-b} option may be independently attached to either or both of
the start and end positions of a field specification, and if it is
inherited from the global options it will be attached to both.
If input lines can contain leading or adjacent blanks and @option{-t}
is not used, then @option{-k} is typically combined with @option{-b} or
an option that implicitly ignores leading blanks (@samp{Mghn}) as otherwise
the varying numbers of leading blanks in fields can cause confusing results.
If the start position in a sort field specifier falls after the end of
the line or after the end field, the field is empty. If the @option{-b}
option was specified, the @samp{.@var{c}} part of a field specification
is counted from the first nonblank character of the field.
@vindex _POSIX2_VERSION
@vindex POSIXLY_CORRECT
On older systems, @command{sort} supports an obsolete origin-zero
syntax @samp{+@var{pos1} [-@var{pos2}]} for specifying sort keys.
The obsolete sequence @samp{sort +@var{a}.@var{x} -@var{b}.@var{y}}
is equivalent to @samp{sort -k @var{a+1}.@var{x+1},@var{b}} if @var{y}
is @samp{0} or absent, otherwise it is equivalent to @samp{sort -k
@var{a+1}.@var{x+1},@var{b+1}.@var{y}}.
This obsolete behavior can be enabled or disabled with the
@env{_POSIX2_VERSION} environment variable (@pxref{Standards
conformance}); it can also be enabled when @env{POSIXLY_CORRECT} is
not set by using the obsolete syntax with @samp{-@var{pos2}} present.
Scripts intended for use on standard hosts should avoid obsolete
syntax and should use @option{-k} instead. For example, avoid
@samp{sort +2}, since it might be interpreted as either @samp{sort
./+2} or @samp{sort -k 3}. If your script must also run on hosts that
support only the obsolete syntax, it can use a test like @samp{if sort
-k 1 </dev/null >/dev/null 2>&1; then @dots{}} to decide which syntax
to use.
Here are some examples to illustrate various combinations of options.
@itemize @bullet
@item
Sort in descending (reverse) numeric order.
@example
sort -n -r
@end example
@item
Run no more that 4 sorts concurrently, using a buffer size of 10M.
@example
sort --parallel=4 -S 10M
@end example
@item
Sort alphabetically, omitting the first and second fields
and the blanks at the start of the third field.
This uses a single key composed of the characters beginning
at the start of the first nonblank character in field three
and extending to the end of each line.
@example
sort -k 3b
@end example
@item
Sort numerically on the second field and resolve ties by sorting
alphabetically on the third and fourth characters of field five.
Use @samp{:} as the field delimiter.
@example
sort -t : -k 2,2n -k 5.3,5.4
@end example
Note that if you had written @option{-k 2n} instead of @option{-k 2,2n}
@command{sort} would have used all characters beginning in the second field
and extending to the end of the line as the primary @emph{numeric}
key. For the large majority of applications, treating keys spanning
more than one field as numeric will not do what you expect.
Also note that the @samp{n} modifier was applied to the field-end
specifier for the first key. It would have been equivalent to
specify @option{-k 2n,2} or @option{-k 2n,2n}. All modifiers except
@samp{b} apply to the associated @emph{field}, regardless of whether
the modifier character is attached to the field-start and/or the
field-end part of the key specifier.
@item
Sort the password file on the fifth field and ignore any
leading blanks. Sort lines with equal values in field five
on the numeric user ID in field three. Fields are separated
by @samp{:}.
@example
sort -t : -k 5b,5 -k 3,3n /etc/passwd
sort -t : -n -k 5b,5 -k 3,3 /etc/passwd
sort -t : -b -k 5,5 -k 3,3n /etc/passwd
@end example
These three commands have equivalent effect. The first specifies that
the first key's start position ignores leading blanks and the second
key is sorted numerically. The other two commands rely on global
options being inherited by sort keys that lack modifiers. The inheritance
works in this case because @option{-k 5b,5b} and @option{-k 5b,5} are
equivalent, as the location of a field-end lacking a @samp{.@var{c}}
character position is not affected by whether initial blanks are
skipped.
@item
Sort a set of log files, primarily by IPv4 address and secondarily by
time stamp. If two lines' primary and secondary keys are identical,
output the lines in the same order that they were input. The log
files contain lines that look like this:
@example
4.150.156.3 - - [01/Apr/2004:06:31:51 +0000] message 1
211.24.3.231 - - [24/Apr/2004:20:17:39 +0000] message 2
@end example
Fields are separated by exactly one space. Sort IPv4 addresses
lexicographically, e.g., 212.61.52.2 sorts before 212.129.233.201
because 61 is less than 129.
@example
sort -s -t ' ' -k 4.9n -k 4.5M -k 4.2n -k 4.14,4.21 file*.log |
sort -s -t '.' -k 1,1n -k 2,2n -k 3,3n -k 4,4n
@end example
This example cannot be done with a single @command{sort} invocation,
since IPv4 address components are separated by @samp{.} while dates
come just after a space. So it is broken down into two invocations of
@command{sort}: the first sorts by time stamp and the second by IPv4
address. The time stamp is sorted by year, then month, then day, and
finally by hour-minute-second field, using @option{-k} to isolate each
field. Except for hour-minute-second there's no need to specify the
end of each key field, since the @samp{n} and @samp{M} modifiers sort
based on leading prefixes that cannot cross field boundaries. The
IPv4 addresses are sorted lexicographically. The second sort uses
@samp{-s} so that ties in the primary key are broken by the secondary
key; the first sort uses @samp{-s} so that the combination of the two
sorts is stable.
@item
Generate a tags file in case-insensitive sorted order.
@smallexample
find src -type f -print0 | sort -z -f | xargs -0 etags --append
@end smallexample
The use of @option{-print0}, @option{-z}, and @option{-0} in this case means
that file names that contain blanks or other special characters are
not broken up
by the sort operation.
@c This example is a bit contrived and needs more explanation.
@c @item
@c Sort records separated by an arbitrary string by using a pipe to convert
@c each record delimiter string to @samp{\0}, then using sort's -z option,
@c and converting each @samp{\0} back to the original record delimiter.
@c
@c @example
@c printf 'c\n\nb\n\na\n'|perl -0pe 's/\n\n/\n\0/g'|sort -z|perl -0pe 's/\0/\n/g'
@c @end example
@item
Use the common @acronym{DSU, Decorate Sort Undecorate} idiom to
sort lines according to their length.
@example
awk '@{print length, $0@}' /etc/passwd | sort -n | cut -f2- -d' '
@end example
In general this technique can be used to sort data that the @command{sort}
command does not support, or is inefficient at, sorting directly.
@item
Shuffle a list of directories, but preserve the order of files within
each directory. For instance, one could use this to generate a music
playlist in which albums are shuffled but the songs of each album are
played in order.
@example
ls */* | sort -t / -k 1,1R -k 2,2
@end example
@end itemize
@node shuf invocation
@section @command{shuf}: Shuffling text
@pindex shuf
@cindex shuffling files
@command{shuf} shuffles its input by outputting a random permutation
of its input lines. Each output permutation is equally likely.
Synopses:
@example
shuf [@var{option}]@dots{} [@var{file}]
shuf -e [@var{option}]@dots{} [@var{arg}]@dots{}
shuf -i @var{lo}-@var{hi} [@var{option}]@dots{}
@end example
@command{shuf} has three modes of operation that affect where it
obtains its input lines. By default, it reads lines from standard
input. The following options change the operation mode:
@table @samp
@item -e
@itemx --echo
@opindex -c
@opindex --echo
@cindex command-line operands to shuffle
Treat each command-line operand as an input line.
@item -i @var{lo}-@var{hi}
@itemx --input-range=@var{lo}-@var{hi}
@opindex -i
@opindex --input-range
@cindex input range to shuffle
Act as if input came from a file containing the range of unsigned
decimal integers @var{lo}@dots{}@var{hi}, one per line.
@end table
@command{shuf}'s other options can affect its behavior in all
operation modes:
@table @samp
@item -n @var{lines}
@itemx --head-count=@var{count}
@opindex -n
@opindex --head-count
@cindex head of output
Output at most @var{count} lines. By default, all input lines are
output.
@item -o @var{output-file}
@itemx --output=@var{output-file}
@opindex -o
@opindex --output
@cindex overwriting of input, allowed
Write output to @var{output-file} instead of standard output.
@command{shuf} reads all input before opening
@var{output-file}, so you can safely shuffle a file in place by using
commands like @code{shuf -o F <F} and @code{cat F | shuf -o F}.
@item --random-source=@var{file}
@opindex --random-source
@cindex random source for shuffling
Use @var{file} as a source of random data used to determine which
permutation to generate. @xref{Random sources}.
@zeroTerminatedOption
@end table
For example:
@example
shuf <<EOF
A man,
a plan,
a canal:
Panama!
EOF
@end example
@noindent
might produce the output
@example
Panama!
A man,
a canal:
a plan,
@end example
@noindent
Similarly, the command:
@example
shuf -e clubs hearts diamonds spades
@end example
@noindent
might output:
@example
clubs
diamonds
spades
hearts
@end example
@noindent
and the command @samp{shuf -i 1-4} might output:
@example
4
2
1
3
@end example
@noindent
These examples all have four input lines, so @command{shuf} might
produce any of the twenty-four possible permutations of the input. In
general, if there are @var{n} input lines, there are @var{n}! (i.e.,
@var{n} factorial, or @var{n} * (@var{n} - 1) * @dots{} * 1) possible
output permutations.
@exitstatus
@node uniq invocation
@section @command{uniq}: Uniquify files
@pindex uniq
@cindex uniquify files
@command{uniq} writes the unique lines in the given @file{input}, or
standard input if nothing is given or for an @var{input} name of
@samp{-}. Synopsis:
@example
uniq [@var{option}]@dots{} [@var{input} [@var{output}]]
@end example
By default, @command{uniq} prints its input lines, except that
it discards all but the first of adjacent repeated lines, so that
no output lines are repeated. Optionally, it can instead discard
lines that are not repeated, or all repeated lines.
The input need not be sorted, but repeated input lines are detected
only if they are adjacent. If you want to discard non-adjacent
duplicate lines, perhaps you want to use @code{sort -u}.
@xref{sort invocation}.
@vindex LC_COLLATE
Comparisons honor the rules specified by the @env{LC_COLLATE}
locale category.
If no @var{output} file is specified, @command{uniq} writes to standard
output.
The program accepts the following options. Also see @ref{Common options}.
@table @samp
@item -f @var{n}
@itemx --skip-fields=@var{n}
@opindex -f
@opindex --skip-fields
Skip @var{n} fields on each line before checking for uniqueness. Use
a null string for comparison if a line has fewer than @var{n} fields. Fields
are sequences of non-space non-tab characters that are separated from
each other by at least one space or tab.
For compatibility @command{uniq} supports an obsolete option syntax
@option{-@var{n}}. New scripts should use @option{-f @var{n}} instead.
@item -s @var{n}
@itemx --skip-chars=@var{n}
@opindex -s
@opindex --skip-chars
Skip @var{n} characters before checking for uniqueness. Use a null string
for comparison if a line has fewer than @var{n} characters. If you use both
the field and character skipping options, fields are skipped over first.
@vindex _POSIX2_VERSION
On older systems, @command{uniq} supports an obsolete option syntax
@option{+@var{n}}.
This obsolete behavior can be enabled or disabled with the
@env{_POSIX2_VERSION} environment variable (@pxref{Standards
conformance}), but portable scripts should avoid commands whose
behavior depends on this variable.
For example, use @samp{uniq ./+10} or @samp{uniq -s 10} rather than
the ambiguous @samp{uniq +10}.
@item -c
@itemx --count
@opindex -c
@opindex --count
Print the number of times each line occurred along with the line.
@item -i
@itemx --ignore-case
@opindex -i
@opindex --ignore-case
Ignore differences in case when comparing lines.
@item -d
@itemx --repeated
@opindex -d
@opindex --repeated
@cindex repeated lines, outputting
Discard lines that are not repeated. When used by itself, this option
causes @command{uniq} to print the first copy of each repeated line,
and nothing else.
@item -D
@itemx --all-repeated[=@var{delimit-method}]
@opindex -D
@opindex --all-repeated
@cindex all repeated lines, outputting
Do not discard the second and subsequent repeated input lines,
but discard lines that are not repeated.
This option is useful mainly in conjunction with other options e.g.,
to ignore case or to compare only selected fields.
The optional @var{delimit-method} tells how to delimit
groups of repeated lines, and must be one of the following:
@table @samp
@item none
Do not delimit groups of repeated lines.
This is equivalent to @option{--all-repeated} (@option{-D}).
@item prepend
Output a newline before each group of repeated lines.
With @option{--zero-terminated} (@option{-z}), use a zero
byte (@acronym{ASCII} @sc{nul}) instead of a newline.
@item separate
Separate groups of repeated lines with a single newline.
With @option{--zero-terminated} (@option{-z}), use a zero
byte (@acronym{ASCII} @sc{nul}) instead of a newline.
This is the same as using @samp{prepend}, except that
no delimiter is inserted before the first group, and hence
may be better suited for output direct to users.
@end table
Note that when groups are delimited and the input stream contains
two or more consecutive blank lines, then the output is ambiguous.
To avoid that, filter the input through @samp{tr -s '\n'} to replace
each sequence of consecutive newlines with a single newline.
This is a @sc{gnu} extension.
@c FIXME: give an example showing *how* it's useful
@item -u
@itemx --unique
@opindex -u
@opindex --unique
@cindex unique lines, outputting
Discard the first repeated line. When used by itself, this option
causes @command{uniq} to print unique lines, and nothing else.
@item -w @var{n}
@itemx --check-chars=@var{n}
@opindex -w
@opindex --check-chars
Compare at most @var{n} characters on each line (after skipping any specified
fields and characters). By default the entire rest of the lines are
compared.
@zeroTerminatedOption
@end table
@exitstatus
@node comm invocation
@section @command{comm}: Compare two sorted files line by line
@pindex comm
@cindex line-by-line comparison
@cindex comparing sorted files
@command{comm} writes to standard output lines that are common, and lines
that are unique, to two input files; a file name of @samp{-} means
standard input. Synopsis:
@example
comm [@var{option}]@dots{} @var{file1} @var{file2}
@end example
@vindex LC_COLLATE
Before @command{comm} can be used, the input files must be sorted using the
collating sequence specified by the @env{LC_COLLATE} locale.
If an input file ends in a non-newline
character, a newline is silently appended. The @command{sort} command with
no options always outputs a file that is suitable input to @command{comm}.
@cindex differing lines
@cindex common lines
With no options, @command{comm} produces three-column output. Column one
contains lines unique to @var{file1}, column two contains lines unique
to @var{file2}, and column three contains lines common to both files.
Columns are separated by a single TAB character.
@c FIXME: when there's an option to supply an alternative separator
@c string, append `by default' to the above sentence.
@opindex -1
@opindex -2
@opindex -3
The options @option{-1}, @option{-2}, and @option{-3} suppress printing of
the corresponding columns (and separators). Also see @ref{Common options}.
Unlike some other comparison utilities, @command{comm} has an exit
status that does not depend on the result of the comparison.
Upon normal completion @command{comm} produces an exit code of zero.
If there is an error it exits with nonzero status.
@macro checkOrderOption{cmd}
If the @option{--check-order} option is given, unsorted inputs will
cause a fatal error message. If the option @option{--nocheck-order}
is given, unsorted inputs will never cause an error message. If
neither of these options is given, wrongly sorted inputs are diagnosed
only if an input file is found to contain unpairable lines. If an
input file is diagnosed as being unsorted, the @command{\cmd\} command
will exit with a nonzero status (and the output should not be used).
Forcing @command{\cmd\} to process wrongly sorted input files
containing unpairable lines by specifying @option{--nocheck-order} is
not guaranteed to produce any particular output. The output will
probably not correspond with whatever you hoped it would be.
@end macro
@checkOrderOption{comm}
@table @samp
@item --check-order
Fail with an error message if either input file is wrongly ordered.
@item --nocheck-order
Do not check that both input files are in sorted order.
Other options are:
@item --output-delimiter=@var{str}
Print @var{str} between adjacent output columns,
rather than the default of a single TAB character.
The delimiter @var{str} may not be empty.
@end table
@node ptx invocation
@section @command{ptx}: Produce permuted indexes
@pindex ptx
@command{ptx} reads a text file and essentially produces a permuted index, with
each keyword in its context. The calling sketch is either one of:
@example
ptx [@var{option} @dots{}] [@var{file} @dots{}]
ptx -G [@var{option} @dots{}] [@var{input} [@var{output}]]
@end example
The @option{-G} (or its equivalent: @option{--traditional}) option disables
all @sc{gnu} extensions and reverts to traditional mode, thus introducing some
limitations and changing several of the program's default option values.
When @option{-G} is not specified, @sc{gnu} extensions are always enabled.
@sc{gnu} extensions to @command{ptx} are documented wherever appropriate in this
document. For the full list, see @xref{Compatibility in ptx}.
Individual options are explained in the following sections.
When @sc{gnu} extensions are enabled, there may be zero, one or several
@var{file}s after the options. If there is no @var{file}, the program
reads the standard input. If there is one or several @var{file}s, they
give the name of input files which are all read in turn, as if all the
input files were concatenated. However, there is a full contextual
break between each file and, when automatic referencing is requested,
file names and line numbers refer to individual text input files. In
all cases, the program outputs the permuted index to the standard
output.
When @sc{gnu} extensions are @emph{not} enabled, that is, when the program
operates in traditional mode, there may be zero, one or two parameters
besides the options. If there are no parameters, the program reads the
standard input and outputs the permuted index to the standard output.
If there is only one parameter, it names the text @var{input} to be read
instead of the standard input. If two parameters are given, they give
respectively the name of the @var{input} file to read and the name of
the @var{output} file to produce. @emph{Be very careful} to note that,
in this case, the contents of file given by the second parameter is
destroyed. This behavior is dictated by System V @command{ptx}
compatibility; @sc{gnu} Standards normally discourage output parameters not
introduced by an option.
Note that for @emph{any} file named as the value of an option or as an
input text file, a single dash @kbd{-} may be used, in which case
standard input is assumed. However, it would not make sense to use this
convention more than once per program invocation.
@menu
* General options in ptx:: Options which affect general program behavior.
* Charset selection in ptx:: Underlying character set considerations.
* Input processing in ptx:: Input fields, contexts, and keyword selection.
* Output formatting in ptx:: Types of output format, and sizing the fields.
* Compatibility in ptx::
@end menu
@node General options in ptx
@subsection General options
@table @samp
@item -G
@itemx --traditional
As already explained, this option disables all @sc{gnu} extensions to
@command{ptx} and switches to traditional mode.
@item --help
Print a short help on standard output, then exit without further
processing.
@item --version
Print the program version on standard output, then exit without further
processing.
@end table
@exitstatus
@node Charset selection in ptx
@subsection Charset selection
@c FIXME: People don't necessarily know what an IBM-PC was these days.
As it is set up now, the program assumes that the input file is coded
using 8-bit @acronym{ISO} 8859-1 code, also known as Latin-1 character set,
@emph{unless} it is compiled for MS-DOS, in which case it uses the
character set of the IBM-PC@. (@sc{gnu} @command{ptx} is not known to work on
smaller MS-DOS machines anymore.) Compared to 7-bit @acronym{ASCII}, the set
of characters which are letters is different; this alters the behavior
of regular expression matching. Thus, the default regular expression
for a keyword allows foreign or diacriticized letters. Keyword sorting,
however, is still crude; it obeys the underlying character set ordering
quite blindly.
@table @samp
@item -f
@itemx --ignore-case
Fold lower case letters to upper case for sorting.
@end table
@node Input processing in ptx
@subsection Word selection and input processing
@table @samp
@item -b @var{file}
@itemx --break-file=@var{file}
This option provides an alternative (to @option{-W}) method of describing
which characters make up words. It introduces the name of a
file which contains a list of characters which can@emph{not} be part of
one word; this file is called the @dfn{Break file}. Any character which
is not part of the Break file is a word constituent. If both options
@option{-b} and @option{-W} are specified, then @option{-W} has precedence and
@option{-b} is ignored.
When @sc{gnu} extensions are enabled, the only way to avoid newline as a
break character is to write all the break characters in the file with no
newline at all, not even at the end of the file. When @sc{gnu} extensions
are disabled, spaces, tabs and newlines are always considered as break
characters even if not included in the Break file.
@item -i @var{file}
@itemx --ignore-file=@var{file}
The file associated with this option contains a list of words which will
never be taken as keywords in concordance output. It is called the
@dfn{Ignore file}. The file contains exactly one word in each line; the
end of line separation of words is not subject to the value of the
@option{-S} option.
@item -o @var{file}
@itemx --only-file=@var{file}
The file associated with this option contains a list of words which will
be retained in concordance output; any word not mentioned in this file
is ignored. The file is called the @dfn{Only file}. The file contains
exactly one word in each line; the end of line separation of words is
not subject to the value of the @option{-S} option.
There is no default for the Only file. When both an Only file and an
Ignore file are specified, a word is considered a keyword only
if it is listed in the Only file and not in the Ignore file.
@item -r
@itemx --references
On each input line, the leading sequence of non-white space characters will be
taken to be a reference that has the purpose of identifying this input
line in the resulting permuted index. For more information about reference
production, see @xref{Output formatting in ptx}.
Using this option changes the default value for option @option{-S}.
Using this option, the program does not try very hard to remove
references from contexts in output, but it succeeds in doing so
@emph{when} the context ends exactly at the newline. If option
@option{-r} is used with @option{-S} default value, or when @sc{gnu} extensions
are disabled, this condition is always met and references are completely
excluded from the output contexts.
@item -S @var{regexp}
@itemx --sentence-regexp=@var{regexp}
This option selects which regular expression will describe the end of a
line or the end of a sentence. In fact, this regular expression is not
the only distinction between end of lines or end of sentences, and input
line boundaries have no special significance outside this option. By
default, when @sc{gnu} extensions are enabled and if @option{-r} option is not
used, end of sentences are used. In this case, this @var{regex} is
imported from @sc{gnu} Emacs:
@example
[.?!][]\"')@}]*\\($\\|\t\\| \\)[ \t\n]*
@end example
Whenever @sc{gnu} extensions are disabled or if @option{-r} option is used, end
of lines are used; in this case, the default @var{regexp} is just:
@example
\n
@end example
Using an empty @var{regexp} is equivalent to completely disabling end of
line or end of sentence recognition. In this case, the whole file is
considered to be a single big line or sentence. The user might want to
disallow all truncation flag generation as well, through option @option{-F
""}. @xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
Manual}.
When the keywords happen to be near the beginning of the input line or
sentence, this often creates an unused area at the beginning of the
output context line; when the keywords happen to be near the end of the
input line or sentence, this often creates an unused area at the end of
the output context line. The program tries to fill those unused areas
by wrapping around context in them; the tail of the input line or
sentence is used to fill the unused area on the left of the output line;
the head of the input line or sentence is used to fill the unused area
on the right of the output line.
As a matter of convenience to the user, many usual backslashed escape
sequences from the C language are recognized and converted to the
corresponding characters by @command{ptx} itself.
@item -W @var{regexp}
@itemx --word-regexp=@var{regexp}
This option selects which regular expression will describe each keyword.
By default, if @sc{gnu} extensions are enabled, a word is a sequence of
letters; the @var{regexp} used is @samp{\w+}. When @sc{gnu} extensions are
disabled, a word is by default anything which ends with a space, a tab
or a newline; the @var{regexp} used is @samp{[^ \t\n]+}.
An empty @var{regexp} is equivalent to not using this option.
@xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
Manual}.
As a matter of convenience to the user, many usual backslashed escape
sequences, as found in the C language, are recognized and converted to
the corresponding characters by @command{ptx} itself.
@end table
@node Output formatting in ptx
@subsection Output formatting
Output format is mainly controlled by the @option{-O} and @option{-T} options
described in the table below. When neither @option{-O} nor @option{-T} are
selected, and if @sc{gnu} extensions are enabled, the program chooses an
output format suitable for a dumb terminal. Each keyword occurrence is
output to the center of one line, surrounded by its left and right
contexts. Each field is properly justified, so the concordance output
can be readily observed. As a special feature, if automatic
references are selected by option @option{-A} and are output before the
left context, that is, if option @option{-R} is @emph{not} selected, then
a colon is added after the reference; this nicely interfaces with @sc{gnu}
Emacs @code{next-error} processing. In this default output format, each
white space character, like newline and tab, is merely changed to
exactly one space, with no special attempt to compress consecutive
spaces. This might change in the future. Except for those white space
characters, every other character of the underlying set of 256
characters is transmitted verbatim.
Output format is further controlled by the following options.
@table @samp
@item -g @var{number}
@itemx --gap-size=@var{number}
Select the size of the minimum white space gap between the fields on the
output line.
@item -w @var{number}
@itemx --width=@var{number}
Select the maximum output width of each final line. If references are
used, they are included or excluded from the maximum output width
depending on the value of option @option{-R}. If this option is not
selected, that is, when references are output before the left context,
the maximum output width takes into account the maximum length of all
references. If this option is selected, that is, when references are
output after the right context, the maximum output width does not take
into account the space taken by references, nor the gap that precedes
them.
@item -A
@itemx --auto-reference
Select automatic references. Each input line will have an automatic
reference made up of the file name and the line ordinal, with a single
colon between them. However, the file name will be empty when standard
input is being read. If both @option{-A} and @option{-r} are selected, then
the input reference is still read and skipped, but the automatic
reference is used at output time, overriding the input reference.
@item -R
@itemx --right-side-refs
In the default output format, when option @option{-R} is not used, any
references produced by the effect of options @option{-r} or @option{-A} are
placed to the far right of output lines, after the right context. With
default output format, when the @option{-R} option is specified, references
are rather placed at the beginning of each output line, before the left
context. For any other output format, option @option{-R} is
ignored, with one exception: with @option{-R} the width of references
is @emph{not} taken into account in total output width given by @option{-w}.
This option is automatically selected whenever @sc{gnu} extensions are
disabled.
@item -F @var{string}
@itemx --flac-truncation=@var{string}
This option will request that any truncation in the output be reported
using the string @var{string}. Most output fields theoretically extend
towards the beginning or the end of the current line, or current
sentence, as selected with option @option{-S}. But there is a maximum
allowed output line width, changeable through option @option{-w}, which is
further divided into space for various output fields. When a field has
to be truncated because it cannot extend beyond the beginning or the end of
the current line to fit in, then a truncation occurs. By default,
the string used is a single slash, as in @option{-F /}.
@var{string} may have more than one character, as in @option{-F ...}.
Also, in the particular case when @var{string} is empty (@option{-F ""}),
truncation flagging is disabled, and no truncation marks are appended in
this case.
As a matter of convenience to the user, many usual backslashed escape
sequences, as found in the C language, are recognized and converted to
the corresponding characters by @command{ptx} itself.
@item -M @var{string}
@itemx --macro-name=@var{string}
Select another @var{string} to be used instead of @samp{xx}, while
generating output suitable for @command{nroff}, @command{troff} or @TeX{}.
@item -O
@itemx --format=roff
Choose an output format suitable for @command{nroff} or @command{troff}
processing. Each output line will look like:
@smallexample
.xx "@var{tail}" "@var{before}" "@var{keyword_and_after}" "@var{head}" "@var{ref}"
@end smallexample
so it will be possible to write a @samp{.xx} roff macro to take care of
the output typesetting. This is the default output format when @sc{gnu}
extensions are disabled. Option @option{-M} can be used to change
@samp{xx} to another macro name.
In this output format, each non-graphical character, like newline and
tab, is merely changed to exactly one space, with no special attempt to
compress consecutive spaces. Each quote character: @kbd{"} is doubled
so it will be correctly processed by @command{nroff} or @command{troff}.
@item -T
@itemx --format=tex
Choose an output format suitable for @TeX{} processing. Each output
line will look like:
@smallexample
\xx @{@var{tail}@}@{@var{before}@}@{@var{keyword}@}@{@var{after}@}@{@var{head}@}@{@var{ref}@}
@end smallexample
@noindent
so it will be possible to write a @code{\xx} definition to take care of
the output typesetting. Note that when references are not being
produced, that is, neither option @option{-A} nor option @option{-r} is
selected, the last parameter of each @code{\xx} call is inhibited.
Option @option{-M} can be used to change @samp{xx} to another macro
name.
In this output format, some special characters, like @kbd{$}, @kbd{%},
@kbd{&}, @kbd{#} and @kbd{_} are automatically protected with a