home *** CD-ROM | disk | FTP | other *** search
/ ftp.pasteur.org/FAQ/ / ftp-pasteur-org-FAQ.zip / FAQ / editor-faq / sed < prev    next >
Internet Message Format  |  2000-04-29  |  133KB

  1. Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!news-out.cwix.com!newsfeed.cwix.com!newsfeed.nyc.globix.net!netnews.com!newsfeed.enteract.com!betanews.enteract.com!not-for-mail
  2. From: epement@jpusa.chi.il.us (Eric Pement)
  3. Newsgroups: alt.comp.editors.batch,comp.editors,alt.answers,comp.answers,news.answers
  4. Subject: sed FAQ, version 014
  5. Followup-To: poster
  6. Date: Fri, 28 Apr 2000 15:14:15 GMT
  7. Organization: EnterAct Corp.
  8. Lines: 3099
  9. Approved: news-answers-request@MIT.EDU
  10. Message-ID: <3909a91b.65039560@news.jpusa.net>
  11. NNTP-Posting-Host: network.jpusa.dsl.enteract.com
  12. X-Trace: news.enteract.com 956934817 1653 207.229.137.224 (28 Apr 2000 15:13:37 GMT)
  13. X-Complaints-To: abuse@enteract.com
  14. NNTP-Posting-Date: 28 Apr 2000 15:13:37 GMT
  15. Summary: Frequently Asked Questions about sed, the stream editor
  16. X-Newsreader: Forte Free Agent 1.11/32.235
  17. Xref: senator-bedfellow.mit.edu alt.comp.editors.batch:2074 comp.editors:43381 alt.answers:48615 comp.answers:40592 news.answers:182315
  18.  
  19. Archive-name: editor-faq/sed
  20. Posting-Frequency: bimonthly
  21. Last-modified: 2000/04/28
  22. Version: 014
  23. URL: http://www.cornerstonemag.com/sed/sedfaq.html
  24. Maintainer: Eric Pement <epement@jpusa.chi.il.us>
  25.  
  26.                              THE SED FAQ
  27.  
  28.                   Frequently Asked Questions about
  29.                        sed, the stream editor
  30.  
  31. CONTENTS:
  32.  
  33. 1. GENERAL INFORMATION
  34. 1.1. Introduction - How this FAQ is organized
  35. 1.2. Latest version of the sed FAQ
  36. 1.3. FAQ revision information
  37. 1.4. How do I add a question/answer to the sed FAQ?
  38. 1.5. FAQ abbreviations
  39. 1.6. Credits and acknowledgements
  40. 1.7. Standard disclaimers
  41.  
  42. 2. BASIC SED
  43. 2.1. What is sed?
  44. 2.2. What versions of sed are there, and where can I get them?
  45.  
  46. 2.2.1. Free versions
  47.  
  48.  2.2.1.1. Unix platforms
  49.  2.2.1.2. OS/2
  50.  2.2.1.3. Microsoft Windows (Win3x, Win9x, WinNT, Win2K)
  51.  2.2.1.4. MS-DOS
  52.  2.2.1.5. CP/M
  53.  
  54. 2.2.2. Shareware and Commercial versions
  55.  
  56.  2.2.2.1. Unix platforms
  57.  2.2.2.2. OS/2
  58.  2.2.2.3. Windows 95/98, Windows NT, Windows 2000
  59.  2.2.2.4. MS-DOS
  60.  
  61. 2.3. Where can I learn to use sed?
  62.  
  63.  2.3.1. Books
  64.  2.3.2. Mailing list
  65.  2.3.3. Tutorials, electronic text
  66.  2.3.4. General web and ftp sites
  67.  
  68. 3. TECHNICAL
  69. 3.1. More detailed explanation of basic sed
  70. 3.2. Common one-line sed scripts. How do I . . . ?
  71.  
  72.       - double/triple-space a file?
  73.       - convert DOS/Unix newlines?
  74.       - delete leading/trailing spaces?
  75.       - do substitutions on all/certain lines?
  76.       - delete consecutive blank lines?
  77.       - delete blank lines at the top/end of the file?
  78.  
  79. 3.3. Addressing and address ranges
  80. 3.4. [reserved]
  81. 3.5. [reserved]
  82. 3.6. Notes about s2p, the sed-to-perl translator
  83. 3.7. GNU/POSIX extensions to regular expressions
  84.  
  85. 4. EXAMPLES
  86. 4.1. How do I perform a case-insensitive search?
  87. 4.2. How do I make changes in only part of a file?
  88. 4.3. How do I change only the first occurrence of a pattern?
  89. 4.4. How do I make substitutions in every file in a directory, or in a
  90.      complete directory tree?
  91.  
  92.  4.4.1 - Perl solution
  93.  4.4.2 - Unix solution
  94.  4.4.3 - DOS solution
  95.  
  96. 4.5. How do I parse a comma-delimited data file?
  97. 4.6. How do I insert a newline into the RHS of a substitution?
  98. 4.7. How do I represent control-codes or non-printable characters?
  99. 4.8. How do I read environment variables with sed?
  100.  
  101.  4.8.1. - on Unix platforms
  102.  4.8.2. - on MS-DOS or 4DOS platforms
  103.  
  104. 4.9. How do I export or pass variables back into the environment?
  105.  
  106.  4.9.1. - on Unix platforms
  107.  4.9.2. - on MS-DOS or 4DOS platforms
  108.  
  109. 4.10. How do I handle shell quoting in sed?
  110. 4.11. How do I delete a block of text if the block contains a certain
  111.       regular expression?
  112. 4.12. How do I locate/print a paragraph of text if the paragraph
  113.       contains a certain regular expression?
  114. 4.13. How do I delete a block of _specific_ consecutive lines?
  115. 4.14. How do I read (insert/add) a file at the top of a textfile?
  116. 4.15. How do I address all the lines between RE1 and RE2, excluding
  117.       the lines themselves?
  118. 4.16. How do I replace "/some/UNIX/path" in a substitution?
  119. 4.17. How do I replace "C:\SOME\DOS\PATH" in a substitution?
  120. 4.18. How do I convert files with toggle characters, like +this+, to
  121.       look like [i]this[/i]?
  122. 4.19. How do I delete only the first occurrence of a pattern?
  123. 4.20. How do I commify a string of numbers?
  124.  
  125. 5. WHY ISN'T THIS WORKING?
  126. 5.1. Why don't my variables like $var get expanded in my sed script?
  127. 5.2. I'm using 'p' to print, but I have duplicate lines sometimes.
  128. 5.3. Why does my DOS version of sed process a file part-way through
  129.      and then quit?
  130. 5.4. My RE isn't matching/deleting what I want it to. (Or, "Greedy vs.
  131.      stingy pattern matching")
  132. 5.5. What is CSDPMI*B.ZIP and why do I need it?
  133. 5.6. Where are the man pages for GNU sed?
  134. 5.7. How do I tell what version of sed I am using?
  135. 5.8. Does sed issue an exit code?
  136. 5.9. The 'r' command isn't inserting the file into the text.
  137. 5.10. Why can't I match or delete a newline using the \n escape               |
  138.       sequence? Why can't I match 2 or more lines using \n?                   |
  139. 5.11. My script aborts with an error message, "event not found".              |
  140.  
  141. 6. OTHER ISSUES
  142. 6.1. I have a problem that stumps me. Where can I get help?
  143. 6.2. How does sed compare with awk, perl, and other utilities?
  144. 6.3. When should I use sed?
  145. 6.4. When should I NOT use sed?
  146. 6.5. When should I ignore sed and use Awk or Perl instead?
  147. 6.6. Known limitations among sed versions
  148. 6.7. Known bugs among sed versions
  149. 6.8. Known incompatibilities between sed versions
  150.  
  151.  6.8.1. Issuing commands from the command line
  152.  6.8.2. Using comments (prefixed by the '#' sign)
  153.  6.8.3. Special syntax in REs
  154.  6.8.4. Word boundaries
  155.  6.8.5. Range addressing with GNU sed and HHsed
  156.  6.8.6. Commands which operate differently                                    |
  157.  
  158. ------------------------------
  159.  
  160. 1. GENERAL INFORMATION
  161.  
  162. 1.1. Introduction - How this FAQ is organized
  163.  
  164.    This FAQ is organized to answer common (and some uncommon)
  165.    questions about sed, quickly. If you see a term or abbreviation in
  166.    the examples that seems unclear, see if the term is defined in
  167.    section 1.5. If not, write us and we'll try to clarify it for the
  168.    next version of the FAQ.
  169.  
  170. 1.2. Latest version of the sed FAQ
  171.  
  172.    The newest version of the sed FAQ is usually here:
  173.  
  174.       http://www.cornerstonemag.com/sed/sedfaq.html
  175.       http://www.cornerstonemag.com/sed/sedfaq.txt
  176.       http://www.dbnet.ece.ntua.gr/~george/sed/sedfaq.html
  177.       http://www.dbnet.ece.ntua.gr/~george/sed/sedfaq.txt
  178.       http://www.ptug.org/sed/sedfaq.html
  179.       http://www.faqs.org/faqs/editor-faq/sed
  180.       ftp://rtfm.mit.edu/pub/faqs/editor-faq/sed
  181.  
  182.    Another FAQ file on sed by a different author can be found here:
  183.  
  184.       http://www.dreamwvr.com/sed-info/sed-faq.html
  185.  
  186. 1.3. FAQ revision information
  187.  
  188.    Changes to this FAQ since the last version are indicated by a
  189.    vertical bar (|) placed in column 78 of the affected lines. To
  190.    remove the vertical bars (use double quotes for MS-DOS):
  191.  
  192.       sed 's/  *|$//' sedfaq.txt > sedfaq2.txt
  193.  
  194.    In the HTML version, vertical bars do not appear. New or altered
  195.    portions of the FAQ are indicated by printing in dark blue type.
  196.  
  197.    In the text version, words needing emphasis may be surrounded by
  198.    the underscore '_' or the asterisk '*'. In the HTML version, these
  199.    are changed to italics and boldface, respectively.
  200.  
  201. 1.4. How do I add a question/answer to the sed FAQ?
  202.  
  203.    Word your question succinctly and clearly, and e-mail it Eric
  204.    Pement <epement@jpusa.org>, indicating your proposed addition to
  205.    the FAQ. We'll post it on the sed-users mailing list (see section
  206.    2.3.2, below) and discuss it there. If some agreement, your
  207.    contribution will be included in the next edition of the FAQ.
  208.  
  209. 1.5. FAQ abbreviations:
  210.  
  211.    files = one or more filenames, separated by whitespace
  212.    RE  = Regular Expressions supported by sed
  213.    LHS = the left-hand side ("find" part) of "s/find/repl/" command
  214.    RHS = the right-hand side ("replace" part) of "s/find/repl/" cmd.
  215.  
  216.    files: "files" stands for one or more filenames entered on the
  217.    command line. The names may include any wildcards your shell
  218.    understands (such as ``zork*'' or ``Aug[4-9].let''). Sed will
  219.    process each filename passed to it by the shell.
  220.  
  221.    RE: For the syntax of Basic Regular Expressions (BREs), type "man
  222.    ed" and read the documentation for regular expressions. A technical
  223.    description of BREs from the Single UNIX Specification, Version 2,
  224.    by The Open Group (joint committee on Unix) is available online at
  225.    <http://www.opengroup.org/onlinepubs/7908799/xbd/re.html#tag_007_003>.     |
  226.    Sed normally supports BREs plus '\n' to match a newline in the
  227.    pattern space and '\xREx' as equivalent to '/RE/', where 'x' is any
  228.    character other than another backslash.
  229.  
  230.    Some versions of sed support supersets of BREs, or "extended
  231.    regular expressions", which offer additional metacharacters for
  232.    increased flexibility. For additional information on extended REs
  233.    in GNU sed, see sections 3.7 ("GNU/POSIX extensions to regular
  234.    expressions") and 6.8.3 ("Special syntax in REs"), below.
  235.  
  236.    LHS: In sed, the LHS may be a string literal (e.g., "foo") or any
  237.    valid regular expression supported by your version of sed. Some
  238.    versions of sed support things like \t for TAB, \r for carriage
  239.    return, \xNN for direct entry of hex codes, etc. Other versions of
  240.    sed do not support this syntax.
  241.  
  242.    RHS: The right-hand side (the replacement part in s/find/replace/)
  243.    is almost always a string literal, with no interpolation of the
  244.    metacharacters (.), (^), ($), ([), or \(...\) -- with the following
  245.    exceptions:  \1 through \9 are replaced by the corresponding group,
  246.    if grouping \(...\) was used in the LHS.  If no grouping was used
  247.    in the LHS, then \1 through \9 are replaced by literal digits. '&'
  248.    is replaced by the entire expression matched on the LHS. To enter a
  249.    literal ampersand or backslash in the RHS, type '\&' or '\\'.
  250.  
  251. 1.6. Credits and acknowledgements
  252.  
  253.    My time spent messing with sed, composing this FAQ, and generally
  254.    doing text manipulation which is unrelated to my job description is
  255.    due to the kind tolerance of the Christian magazine I work for,
  256.    Cornerstone. So, let me say thanks to the mag staff for indulging
  257.    this somewhat unusual "ministry." Please visit this site:
  258.  
  259.       http://www.cornerstonemag.com
  260.  
  261.    Many of the ideas for this FAQ were taken from the Awk FAQ
  262.       http://www.faqs.org/faqs/computer-lang/awk/faq/
  263.       ftp://rtfm.mit.edu/pub/usenet/comp.lang.awk/faq
  264.  
  265.    and from the Perl FAQ
  266.       http://www.perl.com/perl/FAQ
  267.       http://www.perl.com/CPAN/doc/FAQs/FAQ/html/index.html
  268.       ftp://ftp.cdrom.com/pub/perl/CPAN/doc/FAQs/FAQ
  269.  
  270.    The following individuals have contributed significantly to this
  271.    document, and have provided input and wording suggestions for
  272.    questions, answers, and script examples. Credit goes to these
  273.    contributors (in alphabetical order by last name):
  274.  
  275.       Al Aab <af137@freenet*toronto*on*ca>
  276.       Yiorgos Adamopoulos <adamo@softlab*ece*ntua*gr>
  277.       Walter Briscoe <walter@wbriscoe*demon*co*uk>
  278.       Jim Dennis <jadestar@rahul*net>
  279.       Carlos Duarte <cdua@algos*inesc*pt>
  280.       Otavio Exel <oexel@economatica*com*br>
  281.       Mark Katz <mark@ispc001*demon*co*uk>
  282.       Eric Pement <epement@jpusa*org>                                         |
  283.       Greg Pfeiffer <gpfeiffe@yahoo*com>
  284.       Ken Pizzini <ken@halcyon*com>
  285.       Niall Smart <nialls@euristix*ie>
  286.       Simon Taylor <staylor@unisolve*com*au>
  287.       Greg Ubben <gsu@romulus*ncsc*mil>
  288.  
  289.    Note: Periods (.) are replaced with asterisks (*) to foil e-mail
  290.    harvesting and spam-bots.
  291.  
  292. 1.7. Standard disclaimers
  293.  
  294.    While a serious attempt has been made to ensure the accuracy of the
  295.    information presented herein, the contributors and maintainers of
  296.    this document do not claim the absence of errors and make no
  297.    warranties on the information provided. If you notice any errors or
  298.    ambiguous wording, please notify the FAQ maintainer so it can be
  299.    fixed for the next edition.
  300.  
  301. ------------------------------
  302.  
  303. 2. BASIC SED
  304.  
  305. 2.1. What is sed?
  306.  
  307.    "sed" stands for Stream EDitor. Sed is a non-interactive editor,
  308.    written by the late Lee E. McMahon in 1973 or 1974. A brief history
  309.    of sed's origins may be found in an early history of the Unix
  310.    tools, at <http://www.columbia.edu/~rh120/ch106.x09>.
  311.  
  312.    Instead of the user altering a file interactively by moving the
  313.    cursor on the screen (like with Word Perfect), the user sends a
  314.    script of editing instructions to sed, plus the name of the file to
  315.    edit (or the text to be edited may come as output from a pipe). In
  316.    this sense, sed works like a filter -- deleting, inserting and
  317.    changing characters, words, and lines of text. Its range of
  318.    activity goes from small, simple changes to very complex ones.
  319.  
  320.    Sed reads its input from stdin (Unix shorthand for "standard
  321.    input," i.e., the console) or from files (or both), and sends the
  322.    results to stdout ("standard output," normally the console or
  323.    screen). Most people use sed first for its substitution features.
  324.    Sed is often used as a find-and-replace tool.
  325.  
  326.       sed 's/Glenn/Harold/g' oldfile >newfile
  327.  
  328.    will replace every occurrence of "Glenn" with the word "Harold",
  329.    wherever it occurs in the file. The "find" portion is a regular
  330.    expression ("RE"), which can be a simple word or may contain
  331.    special characters to allow greater flexibility (for example, to
  332.    prevent "Glenn" from also matching "Glennon").
  333.  
  334.    My very first use of sed was to add 8 spaces to the left side of a
  335.    file, so when I printed it, the printing wouldn't begin at the
  336.    absolute left edge of a piece of paper.
  337.  
  338.       sed 's/^/        /' myfile >newfile   # my first sed script
  339.       sed 's/^/        /' myfile | lp       # my next sed script
  340.  
  341.    Then I learned that sed could display only one paragraph of a file,
  342.    beginning at the phrase "and where it came" and ending at the
  343.    phrase "for all people". My script looked like this:
  344.  
  345.       sed -n '/and where it came/,/for all people/p' myfile
  346.  
  347.    Sed's normal behavior is to print (i.e., display or show on screen)
  348.    the entire file, including the parts that haven't been altered,
  349.    unless you use the -n switch. The "-n" stands for "no output". This
  350.    switch is almost always used in conjunction with a 'p' command
  351.    somewhere, which says to print only the sections of the file that
  352.    have been specified. The -n switch with the 'p' command allow for
  353.    parts of a file to be printed (i.e., sent to the console).
  354.  
  355.    Next, I found that sed could show me only (say) lines 12-18 of a
  356.    file and not show me the rest. This was very handy when I needed to
  357.    review only part of a long file and I didn't want to alter it.
  358.  
  359.       sed -n 12,18p myfile   # the 'p' stands for print
  360.  
  361.    Likewise, sed could show me everything else BUT those particular
  362.    lines, without physically changing the file on the disk:
  363.  
  364.       sed 12,18d myfile      # the 'd' stands for delete
  365.  
  366.    Sed could also double-space my single-spaced file when it came time
  367.    to print it:
  368.  
  369.       sed G myfile >newfile
  370.  
  371.    If you have many editing commands (for deleting, adding,
  372.    substituting, etc.) which might take up several lines, those
  373.    commands can be put into a separate file and all of the commands in
  374.    the file applied to file being edited:
  375.  
  376.       sed -f script.sed myfile  # 'script.sed' is the file of commands
  377.                                 # 'myfile' is the file being changed
  378.  
  379.    It is not our intention to convert this FAQ file into a full-blown
  380.    sed tutorial (for good tutorials, see section 2.3). Rather, we hope
  381.    this gives the complete novice a few ideas of how sed can be used.
  382.  
  383. 2.2. What versions of sed are there, and where can I get them?
  384.  
  385. 2.2.1. Free versions
  386.  
  387.    Note: "Free" does not mean "public domain" nor does it necessarily
  388.    mean you will never be charged for it. All versions of sed in this
  389.    section except the CP/M versions are based on the GNU general
  390.    public license and are "free software" by that standard (for
  391.    details, see http://www.gnu.org/philosophy/free-sw.html). This
  392.    means you can get the source code and develop it further.
  393.  
  394.    At the URLs listed in this category, sed binaries or source code
  395.    can be downloaded and used without fees or license payments.
  396.  
  397. 2.2.1.1. Unix platforms
  398.  
  399.    GNU sed v3.02.80
  400.    Now a,i,c commands can accept a string after them. Range syntax now
  401.    supports "/RE/,+n" (next n lines) or "/RE/,~n" (till the next line
  402.    which is a multiple of n). NULs permitted in regexes; \n, \t, \a,
  403.    \f, \xHH hex codes supported on LHS and RHS; more changes. An alpha
  404.    test release which (if found bug-free) will become GNU sed version
  405.    3.03. Supersedes GNU sed-3.02a.
  406.       ftp://alpha.gnu.org/pub/gnu/sed/sed-3.02.80.tar.gz
  407.  
  408.    GNU sed v3.02a
  409.    Interim version with most of what is now gsed-3.02.80 (above),
  410.    which supersedes it.
  411.  
  412.    GNU sed v3.02
  413.    This is the latest official version of GNU sed
  414.       ftp://ftp.gnu.org/pub/gnu/sed/sed-3.02.tar.gz
  415.  
  416.    GNU sed v2.05
  417.    This version is superseded by v3.02 and v3.02.80, above.
  418.  
  419.    GNU mirror sites. A list of mirror sites is at:
  420.       http://www.ensta.fr/internet/unix/GNU-archives.html
  421.  
  422.    Precompiled versions:
  423.  
  424.    GNU sed v3.02-4
  425.    source code and binaries for Debian GNU/Linux
  426.       http://www.debian.org/Packages/unstable/base/sed.html
  427.  
  428.    GNU sed v3.02-1
  429.    source code and binaries for Debian GNU/Linux
  430.       http://www.debian.org/Packages/stable/base/sed.html
  431.  
  432.    The 4.4BSD version of sed is available from any 4.4BSD-Lite2 mirror
  433.    site:
  434.       ftp://ftp.ntua.gr/pub/bsd/4.4BSD/usr/src/usr.bin/sed/
  435.  
  436.    For some time, the GNU project <http://www.gnu.org> used Eric S.
  437.    Raymond's version of sed (ESR sed v1.1), but eventually dropped it
  438.    because it had too many built-in limits. In 1991 Howard Helman
  439.    modified the GNU/ESR sed and produced a flexible version of sed
  440.    v1.5 available at several sites (Helman's version permitted things
  441.    like \<...\> to delimit word boundaries, \xHH to enter hex code and
  442.    \n to indicate newlines in the replace string). This version did
  443.    not catch on with the GNU project and their version of sed has
  444.    moved in a similar but different direction.
  445.  
  446.    sed v1.3, by Eric Steven Raymond (released 4 June 1998)
  447.       http://earthspace.net/~esr/sed-1.3.tar.gz
  448.  
  449.    Eric Raymond <esr@snark.thyrsus.com> wrote one of the earliest
  450.    versions of sed. On his website <http://www.tuxedo.org/~esr/> which
  451.    also distributes many freeware utilities he has written or worked
  452.    on, he describes sed v1.1 this way:
  453.  
  454.    "This is the fast, small sed originally distributed in the GNU
  455.    toolkit and still distributed with Minix. The GNU people ditched it
  456.    when they built their own sed around an enhanced regex package --
  457.    but it's still better for some uses (in particular, faster and less
  458.    memory-intensive)." (Version 1.3 fixes an unidentified bug and adds
  459.    the L command to hexdump the current pattern space.)
  460.  
  461. 2.2.1.2. OS/2
  462.  
  463.    GNU sed v3.02.80                                                           |
  464.       http://www2s.biglobe.ne.jp/~vtgf3mpr/gnu/sed.htm                        |
  465.  
  466.    GNU sed v2.05 (requires 'emxrt.zip', below)
  467.       http://oak.oakland.edu/pub/os2/editors/gnused.zip
  468.       http://oak.oakland.edu/pub/os2/emx09c/emxrt.zip
  469.  
  470.    GNU sed v1.06
  471.       http://oak.oakland.edu/pub/os2/editors/sed106.zip
  472.  
  473. 2.2.1.3. Microsoft Windows (Win3x, Win9x, WinNT, Win2K)
  474.  
  475.    GNU sed v3.02.80
  476.    32-bit binaries and docs, using DJGPP compiler. For details on new
  477.    features, see Unix section, above.
  478.       http://www.cornerstonemag.com/sed/sed3028a.zip     # DOS binaries
  479.       ftp://alpha.gnu.org/pub/gnu/sed/sed-3.02.80.tar.gz # source
  480.  
  481.    GNU sed v3.02
  482.    32-bit binaries and source, using DJGPP compiler. Requires 80386 SX
  483.    or better. Also requires 3 CWS*.EXE extenders if run under MS-DOS.
  484.    See section 5.5 ("What is CSDPMI*B.ZIP and why do I need it?"),
  485.    below. This version will run under Windows or under MS-DOS.
  486.  
  487.    The binary archive (sed302b.zip) contains 2 executables, sed.exe
  488.    and gsed.exe.  sed.exe was compiled with the DJGPP regex library,
  489.    which is POSIX.2-compliant and usually runs faster; gsed.exe was
  490.    compiled with the GNU regex library, which though it runs slower
  491.    and is almost POSIX.2-compliant, it has a richer set of regexs and
  492.    will run faster on certain complex regexs which cause the DJGPP
  493.    sed.exe to run extremely slowly.
  494.       ftp://ftp.simtel.net/pub/simtelnet/gnu/djgpp/v2gnu/sed302b.zip
  495.       ftp://ftp.cdrom.com/.27/simtelnet/gnu/djgpp/v2gnu/sed302b.zip
  496.       ftp://ftp.simtel.net/pub/simtelnet/gnu/djgpp/v2gnu/sed302s.zip
  497.       ftp://ftp.cdrom.com/.27/simtelnet/gnu/djgpp/v2gnu/sed302s.zip
  498.  
  499.    GNU sed v2.05
  500.    32-bit binaries, no docs. Requires 80386 DX (SX will not run) and
  501.    must be run in a DOS window or in a full screen DOS session under
  502.    Microsoft Windows. Will not run in MS-DOS mode (outside Win/Win95).
  503.    We recommend using GNU sed v3.02 (above) instead.
  504.       http://www.simtel.net/pub/simtelnet/win95/prog/gsed205b.zip
  505.       ftp://ftp.cdrom.com/.27/simtelnet/win95/prog/gsed205b.zip
  506.  
  507.    GNU sed v1.03
  508.    modified by Frank Whaley.
  509.       ftp://ftp.itribe.net/pub/virtunix/gnused.zip
  510.  
  511.    Again, we recommend avoiding versions of GNU sed other than version
  512.    3.02 or 3.02.80. However, this version appears to be built on gsed
  513.    v1.03 beta as a base and then augmented farther. The authors did
  514.    not give this sed its own version number or name. Gsed v1.03 is
  515.    offered in the "Virtually UN*X" set of Win32 utilities at
  516.    <http://www.itribe.net/virtunix/>. It supports Win 95/98/NT long
  517.    filenames, and runs in a DOS session or DOS window under Microsoft
  518.    Windows, but does not run in DOS mode. This version of sed supports
  519.    hex, decimal, binary, and octal representation in expressions.
  520.  
  521.    The Cygwin toolkit:
  522.       http://sourceware.cygnus.com/cygwin/
  523.  
  524.    Formerly know as "GNU-Win32 tools." According to their home page,
  525.    "The Cygwin tools are Win32 ports of the popular GNU development
  526.    tools for Windows NT, 95 and 98. They function through the use of
  527.    the Cygwin library which provides a UNIX-like API on top of the
  528.    Win32 API." The version of sed used is GNU sed v3.02.
  529.  
  530.    Minimalist GNU-Win32 (Mingw32):
  531.       ftp://agnes.dida.physik.uni-essen.de/home/janjaap/mingw32/binaries/sed-2.05.zip
  532.       http://agnes.dida.physik.uni-essen.de/~janjaap/mingw32/download.html
  533.  
  534.    According to their home page, "The Minimalist GNU-Win32 Package (or
  535.    Mingw32) is simply a set of header files and initialization code
  536.    which allows a GNU compiler to link programs with one of the C
  537.    run-time libraries provided by Microsoft. By default it uses
  538.    CRTDLL, which is built into all Win32 operating systems." The
  539.    download page says Mingw32 programs "behave like you would expect
  540.    from a Windows application. They support drive letters, for
  541.    example. A side effect of using CRTDLL is that Mingw32 is
  542.    thread-safe, while Cygwin32 is not." The version of sed used is GNU
  543.    sed v2.05.
  544.  
  545.    sed v1.5 (a/k/a HHsed), by Howard Helman
  546.    Compiled with Mingw32 for 32-bit environments described above. This
  547.    version should support Win95 long filenames.
  548.       http://www.dbnet.ece.ntua.gr/~george/sed/sed15.exe
  549.       http://www.cornerstonemag.com/sed/sed15exe.zip
  550.  
  551. 2.2.1.4. MS-DOS
  552.  
  553.    sed v1.5 (a/k/a HHsed), by Howard Helman
  554.    uncompiled source code (Turbo C)
  555.       ftp://ftp.simtel.net/pub/simtelnet/msdos/txtutl/sed15.zip
  556.       ftp://ftp.cdrom.com/pub/simtelnet/msdos/txtutl/sed15.zip
  557.       ftp://oak.oakland.edu/pub/simtelnet/msdos/txtutl/sed15.zip
  558.       ftp://uiarchive.uiuc.edu/pub/systems/pc/simtelnet/msdos/txtutl/sed15.zip
  559.  
  560.    DOS executable and documentation
  561.       ftp://ftp.simtel.net/pub/simtelnet/msdos/txtutl/sed15x.zip
  562.       ftp://ftp.cdrom.com/pub/simtelnet/msdos/txtutl/sed15x.zip
  563.       ftp://oak.oakland.edu/pub/simtelnet/msdos/txtutl/sed15x.zip
  564.       ftp://uiarchive.uiuc.edu/pub/systems/pc/simtelnet/msdos/txtutl/sed15x.zip
  565.  
  566.    sedmod v1.0, by Hern Chen
  567.       http://www.ptug.org/sed/SEDMOD10.ZIP
  568.       http://www.cornerstonemag.com/sed/sedmod10.zip
  569.       ftp://garbo.uwasa.fi/pc/unix/sedmod10.zip
  570.       CompuServe DTPFORUM, "PC DTP Tools" library, file SEDMOD.ZIP
  571.  
  572.    GNU sed v3.02.80
  573.    See section 2.2.1.3 ("Microsoft Windows"), above.
  574.  
  575.    GNU sed v3.02
  576.    See section 2.2.1.3 ("Microsoft Windows"), above.
  577.  
  578.    GNU sed v2.05
  579.    Does not run under MS-DOS.
  580.  
  581.    GNU sed v1.18
  582.    32-bit binaries and source, using DJGPP compiler. Requires 80386 SX
  583.    or better. Also requires 3 CWS*.EXE extenders on the path. See
  584.    section 5.5 ("What is CSDPMI*B.ZIP and why do I need it?"), below.
  585.    We recommend using GNU sed v3.02 (above) instead.
  586.       http://www.simtel.net/pub/simtelnet/gnu/djgpp/v2gnu/sed118b.zip
  587.       ftp://ftp.cdrom.com/pub/simtelnet/gnu/djgpp/v2gnu/sed118b.zip
  588.       http://www.simtel.net/pub/simtelnet/gnu/djgpp/v2gnu/sed118s.zip
  589.       ftp://ftp.cdrom.com/pub/simtelnet/gnu/djgpp/v2gnu/sed118s.zip
  590.  
  591.    GNU sed v1.06
  592.    16-bit binaries and source. Should run under any MS-DOS system.
  593.       http://www.simtel.net/pub/simtelnet/gnu/gnuish/sed106.zip
  594.       ftp://ftp.cdrom.com/pub/simtelnet/gnu/gnuish/sed106.zip
  595.  
  596. 2.2.1.5. CP/M
  597.  
  598.    ssed v2.2, by Chuck A. Forsberg
  599.       http://oak.oakland.edu/pub/cpm/txtutl/ssed22.lbr
  600.  
  601.    Written for CP/M, ssed (for "small/stupid stream editor) supports
  602.    only the a(ppend), c(hange), d(elete) and i(nsert) options, and
  603.    apparently doesn't support regular expressions. It does have a -u
  604.    option to "unsqueeze" compressed files and was used mainly in
  605.    conjunction with dif.com for source code maintenance.
  606.  
  607.    change, by Michael M. Rubenstein
  608.       http://oak.oakland.edu/pub/cpm/txtutl/ttools.lbr
  609.  
  610.    Rubenstein probably felt that "sed" was an obscure name, so he
  611.    renamed it CHANGE.COM (the TTOOLS.LBR archive member CHANGE.CZM is
  612.    a "crunched" file). Unlike ssed, change supports full RE's except
  613.    for grouping and backreferences, and its only function is for
  614.    global substitution.
  615.  
  616. 2.2.2. Shareware and Commercial versions
  617.  
  618. 2.2.2.1. Unix platforms
  619.  
  620.       ** Information needed **
  621.  
  622. 2.2.2.2. OS/2
  623.  
  624.    Hamilton Labs:
  625.       http://www.hamiltonlabs.com/cshell.htm
  626.  
  627.    A sizable set of Unix/C shell utilities designed for OS/2. Price is
  628.    $350 in the US, $395 elsewhere, with FedEx shipping, unconditional
  629.    guarantee, unlimited support and free updates. A demo version of
  630.    the suite can be downloaded from this site, but a stand-alone copy
  631.    of sed is not available.
  632.  
  633. 2.2.2.3. Windows 95/98, Windows NT, Windows 2000
  634.  
  635.    Hamilton Labs:
  636.       http://www.hamiltonlabs.com/cshell.htm
  637.  
  638.    A sizable set of Unix/C shell utilities designed for Win9x, WinNT,
  639.    and Win2K. Price is $350 in the US, $395 elsewhere, with FedEx
  640.    shipping, unconditional guarantee, unlimited support and free
  641.    updates. A demo version of the suite can be downloaded from this
  642.    site, but a stand-alone copy of sed is not available.
  643.  
  644.    Interix:
  645.       http://www.interix.com
  646.  
  647.    Interix (formerly known as OpenNT) is advertised as "a complete
  648.    UNIX system environment running natively on Microsoft Windows NT",
  649.    and is licensed and supported by Softway Systems. It offers over
  650.    200 Unix utilities, and supports Unix shells, sockets, networking,
  651.    and more. A single-user edition runs about $200. A free demo or
  652.    evaluation copy will run for 31 days and then quit; to continue
  653.    using it, you must purchase the commercial version.
  654.  
  655.    MKS NuTCRACKER Professional
  656.       http://www.datafocus.com/products/nutc/
  657.  
  658.    A different, yet related product line offered by MKS (Mortice Kern
  659.    Systems, below); the awkward spelling "NuTCRACKER" is intentional.
  660.    Various packages offer hundreds of Unix utilities for Win32
  661.    environments. Sed is not available as a separate product.
  662.  
  663.    UnixDos:
  664.       http://www.unixdos.com
  665.  
  666.    UnixDos is a suite of 82 Unix utilities ported over to the Windows
  667.    environments. There are 16-bit versions for Win 3.1 and 32-bit
  668.    versions for WinNT/Win95. It is distributed as uncrippled shareware
  669.    for the first 30 days. After the test period, the utilities will
  670.    not run and you must pay the registration fee of $50.
  671.  
  672.    Their version of sed supports "\n" in the RHS of expressions, and
  673.    increases the length of input lines to 10,000 characters. By
  674.    special arrangement with the owners, persons who want a licensed
  675.    version of sed *only* (without the other utilities) may pay a
  676.    license fee of $10.
  677.  
  678.    U/WIN:
  679.       http://www.research.att.com/sw/tools/uwin/
  680.  
  681.    U/WIN is a suite of Unix utilities created for WinNT and Win95
  682.    systems. It is owned by AT&T, created by David Korn (author of the
  683.    Unix korn shell), and is freely distributed only to educational
  684.    institutions, AT&T employees, or certain researchers; all others
  685.    must pay a fee after a 90-day evaluation period expires. U/WIN
  686.    operates best with the NTFS (WinNT file system) but will run in
  687.    degraded mode with the FAT file system and in further degraded mode
  688.    under Win95. A minimal installation takes about 25 to 30 megs of
  689.    disk space. Sed is not available as a separate file for download,
  690.    but comes with the suite.
  691.  
  692. 2.2.2.4. MS-DOS
  693.  
  694.    Mix C/Utilities Toolchest                                                  |
  695.       http://www.mixsoftware.com/product/utility.htm                          |
  696.  
  697.    According to their web page, "The C/Utilities Toolchest adds over          |
  698.    40 powerful UNIX utilities to your MS-DOS operating system. The            |
  699.    result is an environment very similar to UNIX operating systems,           |
  700.    yet 100% compatible with MS-DOS programs and commands." The                |
  701.    toolchest costs $19.95, with source code available for an                  |
  702.    additional fee. Mix C's version of sed is not available separately.        |
  703.  
  704.    MKS (Mortice Kern Systems) Toolkit
  705.       http://www.mks.com
  706.  
  707.    Sed comes bundled with the MKS Toolkit, which is distributed only
  708.    as commercial software; it is not available separately.
  709.  
  710.    Thompson Automation Software
  711.       http://www.teleport.com/~thompson/
  712.  
  713.    The Thompson Toolkit contains over 100 familiar Unix utilities,
  714.    including a version of the Unix Korn shell. It runs under MS-DOS,
  715.    OS/2, Win 3.0/3.1, Win95, and WinNT. Sed is one of the utilities,
  716.    though Thompson is better known for its version of awk for DOS,
  717.    TAWK. The toolkit runs about $150; sed is not available separately.
  718.  
  719. 2.3. Where can I learn to use sed?
  720.  
  721. 2.3.1. Books
  722.  
  723.    _Sed & Awk, 2d edition_, by Dale Dougherty & Arnold Robbins
  724.    (Sebastopol, Calif: O'Reilly and Associates, 1997)
  725.    ISBN 1-56592-225-5
  726.       http://www.oreilly.com/catalog/sed2/noframes.html
  727.  
  728.    About 40 percent of this book is devoted to sed, and maybe 50
  729.    percent is devoted to awk. The other 10 percent is given to regular
  730.    expressions and concepts which are common to both tools. If you
  731.    prefer hard copy, this is definitely the best single place to learn
  732.    to use sed, including its advanced features.
  733.  
  734.    The first edition is also very useful. Several typos crept into the
  735.    first printing of the first edition (though if you follow the
  736.    tutorials closely, you'll recognize them right away). A list of
  737.    errors from the first printing of _sed & awk_ is available at
  738.    <http://www.cs.colostate.edu/~dzubera/sedawk.txt>, and errors in
  739.    the 2nd are at <http://www.cs.colostate.edu/~dzubera/sedawk2.txt>,
  740.    though most of these were corrected in later printings. The second
  741.    edition tells how POSIX standards have affected these tools and
  742.    covers the popular GNU versions of sed and awk. Price is about (US)
  743.    $30.00
  744.  
  745.    -----
  746.  
  747.    _Mastering Regular Expressions_, by Jeffrey E. F. Friedl
  748.    (Sebastopol, Calif: O'Reilly and Associates, 1997)
  749.    ISBN 1-56592-257-3
  750.       http://www.oreilly.com/catalog/regex/
  751.       http://enterprise.ic.gc.ca/~jfriedl/regex/index.html
  752.  
  753.    Knowing how to use "regular expressions" is essential to effective
  754.    use of most Unix tools. This book focuses on how regular
  755.    expressions can be best implemented in utilities such as perl, vi,
  756.    emacs, and awk, but also touches on sed as well. Friedl's home page
  757.    (above) gives links to other sites which help students learn to
  758.    master regular expressions. His site also gives a Perl script for
  759.    determining a syntactically valid e-mail address, using regexes:
  760.       http://enterprise.ic.gc.ca/~jfriedl/regex/email-opt.pl
  761.  
  762.    -----
  763.  
  764.    _Awk und Sed_, by Helmut Herold. (Bonn: Addison-Wesley, 1994)
  765.    ISBN 3-89319-685-4
  766.    VVA-Nr. 563-00685-8
  767.  
  768.    The text of this book is in German. Now out of print.
  769.  
  770.    -----
  771.  
  772.    _Linux-Unix-Profitools: awk, sed, lex, yacc und make_, by Helumt
  773.    Herold. (Bonn: Addison-Wesley, 1998)
  774.    ISBN 3-8273-1448-8
  775.  
  776.       http://www.addison-wesley.de:80/katalog/item.ppml?id=00262
  777.  
  778.    The text of this book is in German. (Comments from German-speaking
  779.    reviewers appreciated!)
  780.  
  781. 2.3.2. Mailing list
  782.  
  783.    The informal "seders" mailing list has changed to a Majordomo
  784.    mailing list called "sed-users". Regular and digest versions are
  785.    available. Average mail volume is 12-25 messages per week. For more
  786.    information, address mail to "majordomo@jpusa.org" with any subject        |
  787.    line and the following in the message body:                                |
  788.  
  789.       info sed-users yourname@your.site                                       |
  790.  
  791.    To subscribe, mail to "majordomo@jpusa.org" with any subject line          |
  792.    and one of the following in the message body:                              |
  793.  
  794.       subscribe sed-users yourname@your.site
  795.       subscribe sed-users-digest yourname@your.site
  796.  
  797. 2.3.3. Tutorials, electronic text
  798.  
  799.    The original users manual for sed, by Lee E. McMahon, from the
  800.    7th edition UNIX Manual (1978), with the classic "Kubla Khan"
  801.    example and tutorial, in formatted text format:
  802.       http://www.urc.bl.ac.yu/manuals/progunix/sed.txt
  803.       http://www.softlab.ntua.gr/unix/docs/sed.txt
  804.  
  805.    The source code to the preceding manual. Use "troff -ms sed" to
  806.    print this file properly:
  807.       http://plan9.bell-labs.com/7thEdMan/vol2/sed
  808.       http://cm.bell-labs.com/7thEdMan/vol2/sed
  809.  
  810.    "Do It With Sed", by Carlos Duarte
  811.       http://www.dbnet.ece.ntua.gr/~george/sed/sedtut_1.html
  812.  
  813.    U-SEDIT2.ZIP, by Mike Arst (16 June 1990)
  814.       http://wuarchive.wustl.edu/systems/ibmpc/garbo.uwasa.fi/editor/u-sedit2.zip
  815.       ftp://ftp.cs.umu.se/pub/pc/u-sedit2.zip
  816.       ftp://ftp.uni-stuttgart.de/pub/systems/msdos/util/unixlike/u-sedit2.zip
  817.       ftp://sunsite.icm.edu.pl/vol/d2/garbo/pc/editor/u-sedit2.zip
  818.       ftp://ftp.sogang.ac.kr/.1/msdos_garbo/editor/u-sedit2.zip
  819.  
  820.    U-SEDIT3.ZIP, by Mike Arst (24 Jan. 1992)
  821.       http://www.cornerstonemag.com/sed/u-sedit3.zip
  822.       CompuServe DTPFORUM, "PC DTP Utilities" library, file SEDDOC.ZIP
  823.  
  824.    Another sed FAQ
  825.       http://www.dreamwvr.com/sed-info/sed-faq.html
  826.  
  827.    sed-tutorial, by Felix von Leitner
  828.       http://www.math.fu-berlin.de/~leitner/sed/tutorial.html
  829.  
  830.    "Manipulating text with sed," chapter 14 of the SCO OpenServer
  831.    "Operating System Users Guide"
  832.       http://dontask.caltech.edu:457/cgi-bin/printchapter/OSUserG/BOOKCHAPTER-14.html
  833.       http://www.multisoft.it:457/OSUserG/_Manipulating_text_with_sed.html
  834.  
  835.    "Combining the Bourne-shell, sed and awk in the UNIX environment
  836.    for language analysis," by Lothar M. Schmitt and Kiel T.
  837.    Christianson. This basic tutorial on the Bourne shell, sed and awk
  838.    downloads as a 71-page PostScript file (compressed to 290K with
  839.    gzip). You may need to navigate down from the root to get the file.
  840.       ftp://ftp.u-aizu.ac.jp/u-aizu/doc/Tech-Report/1997/97-2-007.tar.gz
  841.       available upon request from Lothar Schmitt <lothar@u-aizu.ac.jp>
  842.  
  843. 2.3.4. General web and ftp sites
  844.  
  845.    http://seders.icheme.org/                     # Casper Boden-Cummins       |
  846.    http://www.cis.nctu.edu.tw/~gis84806/sed/     # Yao-Jen Chang
  847.    http://www.math.fu-berlin.de/~guckes/sed/     # Sven Guckes
  848.    http://www.math.fu-berlin.de/~leitner/sed/    # Felix von Leitner
  849.    http://www.dbnet.ece.ntua.gr/~george/sed/     # Yiorgos Adamopoulos
  850.    http://www.cornerstonemag.com/sed/            # Eric Pement
  851.  
  852.    http://spacsun.rice.edu/FAQ/sed.html
  853.  
  854.    ftp://algos.inesc.pt/pub/users/cdua/scripts/sed (Carlos Duarte)
  855.    ftp://algos.inesc.pt/pub/users/cdua/scripts/sh  (sed & shell script)
  856.  
  857.    "Handy One-Liners For Sed", compiled by Eric Pement. A large list
  858.    of 1-line sed commands which can be executed from the command line.
  859.    http://www.cornerstonemag.com/sed/sed1line.txt
  860.    http://www.dbnet.ece.ntua.gr/~george/sed/1liners.html
  861.  
  862.    The Single UNIX Specification, Version 2 (technical man page)
  863.    http://www.opengroup.org/onlinepubs/7908799/xcu/sed.html                   |
  864.  
  865.    Getting started with sed
  866.    http://ftp.uni-klu.ac.at/sed/sed.html
  867.  
  868.    Comments in sed
  869.    http://www.bluesky.com.au:457/OSUserG/_Comments_in_sed.html
  870.  
  871.    "Using sed"
  872.    http://www.multisoft.it:457/OSUserG/_Using_sed_main.html
  873.  
  874.    masm to gas converter
  875.    http://www.delorie.com/djgpp/faq/converting/asm2s-sed.html
  876.  
  877.    AltaVista results: "sed script" (744+)
  878.    http://www.altavista.com/cgi-bin/query?pg=q&kl=XX&stype=stext&q=%22sed+script%22
  879.  
  880.    Google results: "sed script" (668+)
  881.    http://www.google.com/search?q=%22sed+script%22
  882.  
  883.    HotBot results: "sed script" (190+)
  884.    http://www.hotbot.com/?MT=%22sed+script%22&SM=MC&DV=0&LG=any&DC=10&DE=2
  885.  
  886.    mail2html.zip
  887.    http://hiwaay.net/~crispen/src/mail2html.zip
  888.  
  889.    customize VIM to aid writing sed scripts
  890.    http://www.fys.uio.no/~hakonrk/vim/syntax/sed.vim
  891.  
  892.    sample uses of sed in batch files and scripts (Benny Pederson)
  893.    http://users.cybercity.dk/~bse26236/batutil/help/SED.HTM
  894.  
  895. ------------------------------
  896.  
  897. 3. TECHNICAL
  898.  
  899. 3.1. More detailed explanation of basic sed
  900.  
  901.    Sed takes a script of editing commands and applies each command, in
  902.    order, to each line of input. After all the commands have been
  903.    applied to the first line of input, that line is output. A second
  904.    input line is taken for processing, and the cycle repeats. Sed
  905.    scripts can address a single line by line number or by matching a
  906.    /RE pattern/ on the line. An exclamation mark '!' after a regex
  907.    ('/RE/!') or line number will select all lines that do NOT match
  908.    that address. Sed can also address a range of lines in the same
  909.    manner, using a comma to separate the 2 addresses.
  910.  
  911.       $d               # delete the last line of the file
  912.       /[0-9]\{3\}/p    # print lines with 3 consecutive digits
  913.       5!s/ham/cheese/  # except on line 5, replace 'ham' with 'cheese'
  914.       /awk/!s/aaa/bb/  # unless 'awk' is found, replace 'aaa' with 'bb'
  915.       17,/foo/d        # delete all lines from line 17 up to 'foo'
  916.  
  917.    Following an address or address range, sed accepts curly braces
  918.    '{...}' so several commands may be applied to that line or to the
  919.    lines matched by the address range. On the command line, semicolons
  920.    ';' separate each instruction and must precede the closing brace.
  921.  
  922.       sed '/Owner:/{s/yours/mine/g;s/your/my/g;s/you/me/g;}' file
  923.  
  924.    Range addresses operate differently depending on which version of
  925.    sed is used (see section 6.8.5, below). For further information on
  926.    using sed, consult the references in section 2.3, above. The online
  927.    manual ("man pages") on Unix/Linux systems may be helpful (try "man
  928.    sed"), but man pages are notoriously obscure for first-time users.
  929.  
  930. 3.2. Common one-line sed scripts
  931.  
  932.    A separate document of over 70 handy "one-line" sed commands is
  933.    available at <http://www.cornerstonemag.com/sed/sed1line.txt>. Here
  934.    are fourteen of the most common sed commands for one-line use.
  935.    MS-DOS users should replace single quotes ('...') with double
  936.    quotes ("...") in these examples. A specific filename ("file")
  937.    usually follows the script, though the input may also come via
  938.    piping ("sort somefile | sed 'somescript'").
  939.  
  940.    # 1. Double space a file
  941.    sed G file
  942.  
  943.    # 2. Triple space a file
  944.    sed 'G;G' file
  945.  
  946.    # 3. Under UNIX: convert DOS newlines (CR/LF) to Unix format
  947.    sed 's/.$//' file    # assumes that all lines end with CR/LF
  948.    sed 's/^M$// file    # in bash/tcsh, press Ctrl-V then Ctrl-M
  949.  
  950.    # 4. Under DOS: convert Unix newlines (LF) to DOS format
  951.    sed 's/$//' file                     # method 1
  952.    sed -n p file                        # method 2
  953.  
  954.    # 5. Delete leading whitespace (spaces/tabs) from front of each line
  955.    # (this aligns all text flush left). '^t' represents a true tab
  956.    # character. Under bash or tcsh, press Ctrl-V then Ctrl-I.
  957.    sed 's/^[ ^t]*//' file
  958.  
  959.    # 6. Delete trailing whitespace (spaces/tabs) from end of each line
  960.    sed 's/[ ^t]*$//' file               # see note on '^t', above
  961.  
  962.    # 7. Delete BOTH leading and trailing whitespace from each line
  963.    sed 's/^[ ^t]*//;s/[ ^]*$//' file    # see note on '^t', above
  964.  
  965.    # 8. Substitute "foo" with "bar" on each line
  966.    sed 's/foo/bar/' file        # replaces only 1st instance in a line
  967.    sed 's/foo/bar/4' file       # replaces only 4th instance in a line
  968.    sed 's/foo/bar/g' file       # replaces ALL instances within a line
  969.  
  970.    # 9. Substitute "foo" with "bar" ONLY for lines which contain "baz"
  971.    sed '/baz/s/foo/bar/g' file
  972.  
  973.    # 10. Delete all CONSECUTIVE blank lines from file except the first.
  974.    # This method also deletes all blank lines from top and end of file.
  975.    # (emulates "cat -s")
  976.    sed '/./,/^$/!d' file       # this allows 0 blanks at top, 1 at EOF
  977.    sed '/^$/N;/\n$/D' file     # this allows 1 blank at top, 0 at EOF
  978.  
  979.    # 11. Delete all leading blank lines at top of file (only).
  980.    sed '/./,$!d' file
  981.  
  982.    # 12. Delete all trailing blank lines at end of file (only).
  983.    sed -e :a -e '/^\n*$/{$d;N;};/\n$/ba' file                                 |
  984.  
  985.    # 13. If a line ends with a backslash, join the next line to it.
  986.    sed -e :a -e '/\\$/N; s/\\\n//; ta' file
  987.  
  988.    # 14. If a line begins with an equal sign, append it to the
  989.    # previous line (and replace the "=" with a single space).
  990.    sed -e :a -e '$!N;s/\n=/ /;ta' -e 'P;D' file
  991.  
  992. 3.3. Addressing and address ranges
  993.  
  994.    Sed commands may have an optional "address" or "address range"
  995.    prefix. If there is no address or address range given, then the
  996.    command is applied to all the lines of the input file or text
  997.    stream. Three commands cannot take an address prefix:
  998.  
  999.    - labels, used to branch or jump within the script
  1000.    - the close brace, '}', which ends the '{' "command"
  1001.    - the '#' comment character, also technically a "command"
  1002.  
  1003.    An address can be a line number (such as 1, 5, 37, etc.), a regular
  1004.    expression (written in the form /RE/ or \xREx where 'x' is any
  1005.    character other than '\' and RE is the regular expression), or the
  1006.    dollar sign ($), representing the last line of the file. An
  1007.    exclamation mark (!) after an address or address range will apply
  1008.    the command to every line EXCEPT the ones named by the address. A
  1009.    null regex ("//") will be replaced by the last regex which was
  1010.    used. Also, some seds do not support \xREx as regex delimiters.
  1011.  
  1012.       5d               # delete line 5 only
  1013.       5!d              # delete every line except line 5
  1014.       /RE/s/LHS/RHS/g  # substitute only if RE occurs on the line
  1015.       /^$/b label      # if the line is blank, branch to ':label'
  1016.       /./!b label      # ... another way to write the same command
  1017.       \%.%!b label     # ... yet another way to write this command
  1018.       $!N              # on all lines but the last, get the Next line
  1019.  
  1020.    Note that an embedded newline can be represented in an address by
  1021.    the symbol \n, but this syntax is needed only if the script puts 2
  1022.    or more lines into the pattern space via the N, G, or other
  1023.    commands. The \n symbol does *not* match the newline at an
  1024.    end-of-line because when sed reads each line into the pattern space
  1025.    for processing, it strips off the trailing newline, processes the
  1026.    line, and adds a newline back when printing the line to standard
  1027.    output. To match the end-of-line, use the '$' metacharacter, as
  1028.    follows:
  1029.  
  1030.       /tape$/       # matches the word 'tape' at the end of a line
  1031.       /tape$deck/   # matches the word 'tape$deck' with a literal '$'
  1032.       /tape\ndeck/  # matches 'tape' and 'deck' with a newline between
  1033.  
  1034.    The following sed commands usually accept *only* a single address.
  1035.    All other commands (except labels, '}', and '#') accept both single
  1036.    addresses and address ranges.
  1037.  
  1038.       =       print to stdout the line number of the current line
  1039.       a       after printing the current line, append "text" to stdout
  1040.       i       before printing the current line, insert "text" to stdout
  1041.       q       quit after the current line is matched
  1042.       r file  prints contents of "file" to stdout after line is matched
  1043.  
  1044.    Note that we said "usually." If you need to apply the '=', 'a',
  1045.    'i', or 'r' commands to each and every line within an address
  1046.    range, this behavior can be coerced by the use of braces. Thus,
  1047.    "1,9=" is an invalid command, but "1,9{=;}" will print each line
  1048.    number followed by its line for the first 9 lines (and then print
  1049.    the rest of the rest of the file normally).
  1050.  
  1051.    Address ranges occur in the form
  1052.  
  1053.       <address1>,<address2>    or    <address1>,<address2>!
  1054.  
  1055.    where the address can be a line number or a standard /regex/.
  1056.    <address2> can also be a dollar sign, indicating the end of file.
  1057.    Under HHsed and gsed302a, <address2> may also be a notation of the
  1058.    form +num, indicating the next _num_ lines after <address1> is
  1059.    matched.
  1060.  
  1061.    Address ranges are:
  1062.  
  1063.    (1) Inclusive. The range "/From here/,/eternity/" matches all the
  1064.    lines containing "From here" up to and including the line
  1065.    containing "eternity". It will not stop on the line just prior to
  1066.    "eternity". (If you don't like this, see section 4.15.)
  1067.  
  1068.    (2) Plenary. They always match full lines, not just parts of lines.
  1069.    In other words, a command to change or delete an address range will
  1070.    change or delete whole lines; it won't stop in the middle of a
  1071.    line.
  1072.  
  1073.    (3) Multilinear. Address ranges normally match 2 lines or more. The
  1074.    second address will never match the same line the first address
  1075.    did; therefore a valid address range always spans at least two
  1076.    lines, with these exceptions which match only one line:
  1077.  
  1078.    - if the first address matches the last line of the file
  1079.    - if using the syntax "/RE/,3" and /RE/ occurs only once in the
  1080.      file at line 3 or below
  1081.    - if using HHsed v1.5. See section 6.8.5.
  1082.  
  1083.    (4) Minimalist. In address ranges with /regex/ as <address2>, the
  1084.    range "/foo/,/bar/" will stop at the first "bar" it finds, provided
  1085.    that "bar" occurs on a line below "foo". If the word "bar" occurs
  1086.    on several lines below the word "foo", the range will match all the
  1087.    lines from the first "foo" up to the first "bar". It will not
  1088.    continue hopping ahead to find more "bar"s. In other words, address
  1089.    ranges are not "greedy," like regular expressions.
  1090.  
  1091.    (5) Repeating. An address range will try to match more than one
  1092.    block of lines in a file. However, the blocks cannot nest. In
  1093.    addition, a second match will not "take" the last line of the
  1094.    previous block.  For example, given the following text,
  1095.  
  1096.       start
  1097.       stop  start
  1098.       stop
  1099.  
  1100.    the sed command '/start/,/stop/d' will only delete the first two
  1101.    lines. It will not delete all 3 lines.
  1102.  
  1103.    (6) Relentless. If the address range finds a "start" match but
  1104.    doesn't find a "stop", it will match every line from "start" to the
  1105.    end of the file. Thus, beware of the following behaviors:
  1106.  
  1107.       /RE1/,/RE2/  # if /RE2/ is not found, matches from /RE1/ to the
  1108.                    # end-of-file
  1109.  
  1110.       20,/RE/      # if /RE/ is not found, matches from line 20 to the
  1111.                    # end-of-file
  1112.  
  1113.       /RE/,30      # if /RE/ occurs any time after line 30, each
  1114.                    # occurrence will be matched in HHsed, sedmod, and
  1115.                    # gsed302. GNU sed v2.05 and 1.18 will match from
  1116.                    # the 2nd occurrence of /RE/ to the end-of-file.
  1117.  
  1118.    If these behaviors seem strange, remember that they occur because
  1119.    sed does not look "ahead" in the file. Doing so would stop sed from
  1120.    being a stream editor and have adverse effects on its efficiency.
  1121.    If these behaviors are undesirable, they can be circumvented or
  1122.    corrected by the use of nested testing within braces. The following
  1123.    scripts work under GNU sed 3.02:
  1124.  
  1125.       # Execute your_commands on range "/RE1/,/RE2/", but if /RE2/ is
  1126.       # not found, do nothing.
  1127.       /RE1/{:a;N;/RE2/!ba;your_commands;}
  1128.  
  1129.       # Execute your_commands on range "20,/RE/", but if /RE/ is not
  1130.       # found, do nothing.
  1131.       20{:a;N;/RE/!ba;your_commands;}
  1132.  
  1133.    As a side note, once we've used N to "slurp" lines together to test
  1134.    for the ending expression, the pattern space will have gathered
  1135.    many lines (possibly thousands) together and concatenated them as a
  1136.    single expression, with the \n sequence marking line breaks. The
  1137.    REs *within* the pattern space may have to be modified (e.g., you
  1138.    must write '/\nStart/' instead of '/^Start/' and '/[^\n]*/' instead
  1139.    of '/.*/') and other standard sed commands will be unavailable or
  1140.    difficult to use.
  1141.  
  1142.       # Execute your_commands on range "/RE/,30", but if /RE/ occurs
  1143.       # on line 31 or later, do not match it.
  1144.       1,30{/RE/,$ your_commands;}
  1145.  
  1146.    For related suggestions on using address ranges, see sections 4.2,
  1147.    4.15, and 4.19 of this FAQ. Note that HHsed contains a bug or
  1148.    nonstandard feature in how it implements address ranges; also, GNU
  1149.    sed 3.02a supports a zero (0) in addressing. For more details, see
  1150.    section 6.8.5 ("Range addressing with GNU sed and HHsed").
  1151.  
  1152. 3.4. [reserved]
  1153.  
  1154. 3.5. [reserved]
  1155.  
  1156. 3.6. Notes about s2p, the sed-to-perl translator
  1157.  
  1158.    s2p (sed to perl) is a Perl program to convert sed scripts into the
  1159.    Perl programming language; it is included with many versions of
  1160.    Perl. These problems have been found when using s2p:
  1161.  
  1162.    (1) Doesn't recognize the semicolon properly after s/// commands.
  1163.  
  1164.       s/foo/bar/g;
  1165.  
  1166.    (2) Doesn't trim trailing whitespace after s/// commands. Even lone
  1167.    trailing spaces, without comments, produce an error.
  1168.  
  1169.    (3) Doesn't handle multiple commands within braces. E.g.,
  1170.  
  1171.       1,4{=;G;}
  1172.  
  1173.    will produce perl code with missing braces, and miss the second "G"
  1174.    command as well. In fact, any commands after the first one are 
  1175.    missed in the perl output script, and the output perl script will 
  1176.    also contain mismatched braces.
  1177.  
  1178. 3.7. GNU/POSIX extensions to regular expressions
  1179.  
  1180.    GNU sed supports "character classes" in addition to regular
  1181.    character sets, such as [0-9A-F]. Like regular character sets,
  1182.    character classes represent any single character within a set.
  1183.  
  1184.    "Character classes are a new feature introduced in the POSIX
  1185.    standard. A character class is a special notation for describing
  1186.    lists of characters that have a specific attribute, but where the
  1187.    actual characters themselves can vary from country to country
  1188.    and/or from character set to character set. For example, the notion
  1189.    of what is an alphabetic character differs in the USA and in
  1190.    France." [quoted from the docs for GNU awk v3.0.3]
  1191.  
  1192.    Though character classes don't generally conserve space on the
  1193.    line, they help make scripts portable for international use. The
  1194.    equivalent character sets *for U.S. users* follow:
  1195.  
  1196.       [[:alnum:]]  - [A-Za-z0-9]     Alphanumeric characters
  1197.       [[:alpha:]]  - [A-Za-z]        Alphabetic characters
  1198.       [[:blank:]]  - [ \x09]         Space or tab characters only
  1199.       [[:cntrl:]]  - [\x00-\x19\x7F] Control characters
  1200.       [[:digit:]]  - [0-9]           Numeric characters
  1201.       [[:graph:]]  - [!-~]           Printable and visible characters
  1202.       [[:lower:]]  - [a-z]           Lower-case alphabetic characters
  1203.       [[:print:]]  - [ -~]           Printable (non-Control) characters
  1204.       [[:punct:]]  - [!-/:-@[-`{-~]  Punctuation characters
  1205.       [[:space:]]  - [ \t\v\f]       All whitespace chars
  1206.       [[:upper:]]  - [A-Z]           Upper-case alphabetic characters
  1207.       [[:xdigit:]] - [0-9a-fA-F]     Hexadecimal digit characters
  1208.  
  1209.    Note that [[:graph:]] does not match the space " ", but [[:print:]]
  1210.    does. Some character classes may (or may not) match characters in
  1211.    the high ASCII range (ASCII 128-255 or 0x80-0xFF), depending on
  1212.    which C library was used to compile sed. For non-English languages,
  1213.    [[:alpha:]] and other classes may also match high ASCII characters.
  1214.  
  1215. ------------------------------
  1216.  
  1217. 4. EXAMPLES
  1218.  
  1219. 4.1. How do I perform a case-insensitive search?
  1220.  
  1221.    Use GNU sed v3.02 (or higher) with the I flag ("/regex/I" or
  1222.    "s/LHS/RHS/I"). Or use sedmod with the -i switch on the command
  1223.    line. With other versions of sed this is not easy to do, so some
  1224.    people use GNU awk (gawk), mawk, or perl, since these programs have
  1225.    options for case-insensitive searches. In gawk/mawk, use "BEGIN
  1226.    {IGNORECASE=1}" and in perl, "/regex/i". For sed, here are three
  1227.    solutions:
  1228.  
  1229.    Solution 1: convert everything to upper case and search normally
  1230.  
  1231.       # sed script, solution 1
  1232.       h;          # copy the original line to the hold space
  1233.                   # convert the pattern space to solid caps
  1234.       y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/
  1235.                   # now we can search for the word "CARLOS"
  1236.       /CARLOS/ {
  1237.            # add or insert lines. Note: "s/.../.../" will not work
  1238.            # here because we are searching a modified pattern
  1239.            # space and are not printing the pattern space.
  1240.       }
  1241.       x;          # get back the original pattern space
  1242.                   # the original pattern space will be printed
  1243.  
  1244.    Solution 2: search for both cases
  1245.  
  1246.    Often, proper names will either start with all lower-case ("unix"),
  1247.    with an initial capital letter ("Unix") or occur in solid caps
  1248.    ("UNIX"). There may be no need to search for every possibility.
  1249.  
  1250.       /UNIX/b match
  1251.       /[Uu]nix/b match
  1252.  
  1253.    Solution 3: search for all possible cases
  1254.  
  1255.       # If all else fails, search for any possible combination
  1256.       /[Ca][Aa][Rr][Ll][Oo][Ss]/...
  1257.  
  1258.    Bear in mind that as the pattern length increases, this solution
  1259.    becomes an order of magnitude slower than the one of Solution 1, at
  1260.    least with some implementations of sed.
  1261.  
  1262. 4.2. How do I make changes in only part of a file?
  1263.  
  1264.    Select parts of a file for changing by naming a range of lines
  1265.    either by number (e.g., lines 1-20), by RE (between the words "foo"
  1266.    and "bar"), or by some combination of the two. For multiple
  1267.    changes, put the substitution command between braces {...}.
  1268.  
  1269.       # replace only between lines 1 and 20
  1270.       1,20 s/Johnson/White/g
  1271.  
  1272.       # replace everywhere EXCEPT between lines 1 and 20
  1273.       1,20 !s/Johnson/White/g
  1274.  
  1275.       # replace only between words "foo" and "bar"
  1276.       /foo/,/bar/ { s/Johnson/White/g; s/Smith/Wesson/g; }
  1277.  
  1278.       # replace only from the words "ENDNOTES:" to the end of file
  1279.       /ENDNOTES:/,$ { s/Schaff/Herzog/g; s/Kraft/Ebbing/g; }
  1280.  
  1281.    For technical details on using address ranges, see section 3.3
  1282.    ("Addressing and Address ranges").
  1283.  
  1284. 4.3. How do I change only the first occurrence of a pattern?
  1285.  
  1286.    To replace the regex "LHS" with "RHS", do this:
  1287.  
  1288.       gsed '0,/LHS/s//RHS/'                       # GNU sed 3.02a
  1289.       sed -e '1s/LHS/RHS/;t' -e '1,/LHS/s//RHS/'  # other seds
  1290.  
  1291.    If you know the pattern *won't* occur on the first line, omit the
  1292.    first -e and the statement following it.
  1293.  
  1294. 4.4. How do I make substitutions in every file in a directory, or in a
  1295.      complete directory tree?
  1296.  
  1297. 4.4.1. - Perl solution
  1298.  
  1299.    (Yes, we know this is a FAQ file for sed, not perl, but the
  1300.    solution is so simple that it has to be noted. Also, perl and
  1301.    sed share a very similar syntax here.)
  1302.  
  1303.       perl -pi.bak -e 's|foo|bar|g' filelist     # or
  1304.       perl -pi.bak -e 's|foo|bar|g' `find /pathname -name "filespec"`
  1305.  
  1306.    For each file in the filelist, perl renames the source file to
  1307.    "filename.bak"; the modified file gets the original filename.
  1308.    Change '-pi.bak' to '-pi' if you don't need backup copies. (Note
  1309.    the use of s||| instead of s/// here, and in the scripts below.
  1310.    The vertical bars in the 's' command lets you replace '/some/path'
  1311.    with '/another/path', accommodating slashes in the LHS and RHS.)
  1312.  
  1313. 4.4.2. - Unix solution
  1314.  
  1315.    For all files in a single directory, assuming they end with *.txt
  1316.    and you have no files named "[anything].txt.bak" already, use a
  1317.    shell script:
  1318.  
  1319.       #! /bin/sh
  1320.       # Source files are saved as "filename.txt.bak" in case of error
  1321.       # The '&&' after cp is an additional safety feature
  1322.       for file in *.txt
  1323.       do
  1324.          cp $file $file.bak &&
  1325.          sed 's|foo|bar|g' $file.bak >$file
  1326.       done
  1327.  
  1328.    To do an entire directory tree, use the Unix utility find, like so
  1329.    (thanks to Jim Dennis <jadestar@rahul.net> for this script):
  1330.  
  1331.       #! /bin/sh
  1332.       # filename: replaceall
  1333.       find . -type f -name '*.txt' -print | while read i
  1334.       do
  1335.          sed 's|foo|bar|g' $i > $i.tmp && mv $i.tmp $i
  1336.       done
  1337.  
  1338.    This previous shell script recurses through the directory tree,
  1339.    finding only files in the directory (not symbolic links, which will
  1340.    be encountered by the shell command "for file in *.txt", above). To
  1341.    preserve file permissions and make backup copies, use the 2-line cp
  1342.    routine of the earlier script instead of "sed ... && mv ...". By
  1343.    replacing the sed command 's|foo|bar|g' with something like
  1344.  
  1345.       sed "s|$1|$2|g" ${i}.bak > $i
  1346.  
  1347.    using double quotes instead of single quotes, the user can also
  1348.    employ positional parameters on the shell script command tail, thus
  1349.    reusing the script from time to time. For example,
  1350.  
  1351.       replaceall East West
  1352.  
  1353.    would modify all your *.txt files in the current directory.
  1354.  
  1355. 4.4.3. - DOS solution:
  1356.  
  1357.    MS-DOS users should use two batch files like this:
  1358.  
  1359.       @echo off
  1360.       :: MS-DOS filename: REPLACE.BAT
  1361.       ::
  1362.       :: Create a destination directory to put the new files.
  1363.       :: Note: The next command will fail under Novel Netware
  1364.       :: below version 4.10 unless "SHOW DOTS=ON" is active.
  1365.       if not exist .\NEWFILES\NUL mkdir NEWFILES
  1366.       for %%f in (*.txt) do CALL REPL_2.BAT %%f
  1367.       echo Done!!
  1368.       :: =======End of the first batch file====
  1369.  
  1370.       @echo off
  1371.       :: MS-DOS filename: REPL_2.BAT
  1372.       ::
  1373.       sed "s/foo/bar/g" %1 > NEWFILES\%1
  1374.       :: =======End of the second batch file===
  1375.  
  1376.    When finished, the current directory contains all the original
  1377.    files, and the newly-created NEWFILES subdirectory contains the
  1378.    modified *.TXT files. Do not attempt a command like
  1379.  
  1380.       for %%f in (*.txt) do sed "s/foo/bar/g" %%f >NEWFILES\%%f
  1381.  
  1382.    under any version of MS-DOS because the output filename will be
  1383.    created as a literal '%f' in the NEWFILES directory before the
  1384.    %%f is expanded to become each filename in (*.txt). This occurs
  1385.    because MS-DOS creates output filenames via redirection commands
  1386.    before it expands "for..in..do" variables.
  1387.  
  1388.    To recurse through an entire directory tree in MS-DOS requires a
  1389.    batch file more complex than we have room to describe. Examine the
  1390.    file SWEEP.BAT in Timo Salmi's great archive of batch tricks,
  1391.    TSBAT61.ZIP, located at <ftp://garbo.uwasa.fi/pc/ts/tsbat61.zip>,          |
  1392.    or get an external program designed for directory recursion. Here          |
  1393.    are some recommended programs for directory recursion. The first           |
  1394.    one, FORALL, runs under either OS/2 or DOS. Unfortunately, none of         |
  1395.    these supports Win9x long filenames.                                       |
  1396.       ftp://hobbes.nmsu.edu/pub/os2/util/disk/forall72.zip                    |
  1397.       http://www.geocities.com/SiliconValley/Lakes/2414/fortn711.zip
  1398.       http://garbo.uwasa.fi/pc/filefind/target15.zip
  1399.  
  1400. 4.5. How do I parse a comma-delimited data file?
  1401.  
  1402.    Comma-delimited data files can come in several forms, requiring
  1403.    increasing levels of complexity in parsing and handling:
  1404.  
  1405.    (a) No quotes, no internal commas
  1406.  
  1407.       1001,John Smith,PO Box 123,Chicago,IL,60699
  1408.       1002,Mary Jones,320 Main,Denver,CO,84100,
  1409.  
  1410.    (b) Like (a), with quotes around each field
  1411.  
  1412.       "1003","John Smith","PO Box 123","Chicago","IL","60699"
  1413.       "1004","Mary Jones","320 Main","Denver","CO","84100"
  1414.  
  1415.    (c) Like (b), with embedded commas
  1416.  
  1417.       "1005","Tom Hall, Jr.","61 Ash Ct.","Niles","OH","44446"
  1418.       "1006","Bob Davis","429 Pine, Apt. 5","Boston","MA","02128"
  1419.  
  1420.    (d) Like (c), with embedded commas and quotes
  1421.  
  1422.       "1007","Sue "Red" Smith","19 Main","Troy","MI","48055"
  1423.       "1008","Joe "Hey, guy!" Hall","POB 44","Reno","NV","89504"
  1424.  
  1425.    In each example above, we have 7 fields and 6 commas which function
  1426.    as field separators. Case (c) is a very typical form of these data
  1427.    files, with double quotes used to enclose each field and to protect
  1428.    internal commas (such as "Tom Hall, Jr.") from interpretation as
  1429.    field separators. However, many times the data may include both
  1430.    embedded quotation marks as well as embedded commas, as seen by
  1431.    case (d), above.
  1432.  
  1433.    Before handling a comma-delimited data file, make sure that you
  1434.    fully understand its format and check the integrity of the data.
  1435.    Does each line contain the same number of fields? Should certain
  1436.    fields be composed only of numbers or of two-letter state
  1437.    abbreviations in all caps? Sed (or awk or perl) should be used to
  1438.    validate the integrity of the data file before you attempt to alter
  1439.    it or extract particular fields from the file.
  1440.  
  1441.    After ensuring that each line has a valid number of fields, use sed
  1442.    to locate and modify individual fields, using the \(...\) grouping
  1443.    command where needed.
  1444.  
  1445.    In case (a):
  1446.  
  1447.       sed 's/^[^,]*,[^,]*,[^,]*,[^,]*,/.../'
  1448.               ^     ^     ^
  1449.               |     |     |_ 3rd field
  1450.               |     |_______ 2nd field
  1451.               |_____________ 1st field
  1452.  
  1453.       # Unix script to delete the second field for case (a)
  1454.       sed 's/^\([^,]*\),[^,]*,/\1,,/' file
  1455.  
  1456.       # Unix script to change field 1 to 9999 for case (a)
  1457.       sed 's/^[^,]*,/9999,/' file
  1458.  
  1459.    In cases (b) and (c):
  1460.  
  1461.       sed 's/^"[^"]*","[^"]*","[^"]*","[^"]*",/.../'
  1462.                1st--   2nd--   3rd--   4th--
  1463.  
  1464.       # Unix script to delete the second field for case (c)
  1465.       sed 's/^\("[^"]*"\),"[^"]*",/\1,"",/' file
  1466.  
  1467.       # Unix script to change field 1 to 9999 for case (c)
  1468.       sed 's/^"[^"]*",/"9999",/' file
  1469.  
  1470.    In case (d):
  1471.  
  1472.    One way to parse such files is to replace the 3-character field
  1473.    separator "," with an unused character like the tab or vertical
  1474.    bar. (Technically, the field separator is only the comma while the
  1475.    fields are surrounded by "double quotes", but the net _effect_ is
  1476.    that fields are separated by quote-comma-quote, with quote
  1477.    characters added to the beginning and end of each record.) Search
  1478.    your datafile _first_ to make sure that your character appears
  1479.    nowhere in it!
  1480.  
  1481.       sed -n '/|/p' file        # search for any instance of '|'
  1482.       # if it's not found, we can use the '|' to separate fields
  1483.  
  1484.    Then replace the 3-character field separator and parse as before:
  1485.  
  1486.       # sed script to delete the second field for case (d)
  1487.       s/","/|/g;                  # global change of "," to bar
  1488.       s/^\([^|]*\)|[^|]|/\1||/;   # delete 2nd field
  1489.       s/|/","/g;                  # global change of bar back to ","
  1490.  
  1491.       # sed script to change field 1 to 9999 for case (d)
  1492.       # Remember to accommodate leading and trailing quote marks
  1493.       s/","/|/g;
  1494.       s/^[^|]*|/"9999|/;
  1495.       s/|/","/g;
  1496.  
  1497.    Note that this technique works only if _each_ and _every_ field is
  1498.    surrounded with double quotes, including empty fields. If your
  1499.    datafile does not look like case (d), above, or if it omits quote
  1500.    marks around empty fields or numeric values, then the complexity of
  1501.    the script would probably not be worth the effort to write it in
  1502.    sed. For such a case, you should use perl. This question is
  1503.    addressed in the Perl FAQ, at question 4.28: "How can I split a
  1504.    [character] delimited string except when inside [character]?"
  1505.  
  1506. 4.6. How do I insert a newline into the RHS of a substitution?
  1507.  
  1508.    Six versions of sed permit '\n' to be typed directly into the RHS,
  1509.    which is then converted to a newline on output: gsed-3.02.80,
  1510.    gsed-3.02a, gsed103 (with the -x switch), HHsed (a/k/a sed14),
  1511.    sedmod, and UnixDOS sed. The _easiest_ solution is to use one of
  1512.    these versions.
  1513.  
  1514.    For other versions of sed, try one of the following:
  1515.  
  1516.    (a) Insert an unused character and pipe the output through tr:
  1517.  
  1518.       echo twolines | sed 's/two/& new=/' | tr "=" "\n"   # produces
  1519.       two new
  1520.       lines
  1521.  
  1522.    (b) Use two backslashes (\\) from the shell prompt. Using bash:
  1523.  
  1524.       [bash-prompt]$ echo twolines | sed "s/two/& new\\
  1525.       >/"
  1526.       two new
  1527.       lines
  1528.       [bash-prompt]$
  1529.  
  1530.    (c) Write a multi-line script and use the backslash (\) in the
  1531.    middle of the "replace" portion:
  1532.  
  1533.       sed -f newline.sed files
  1534.  
  1535.       # newline.sed
  1536.       s/twolines/two new\
  1537.       lines/g
  1538.  
  1539.    Some versions of sed may not need the trailing backslash. If so,
  1540.    remove it.
  1541.  
  1542.    (d) Use the "G" command:
  1543.  
  1544.    G appends a newline, plus the contents of the hold space to the end
  1545.    of the pattern space. If the hold space is empty, a newline is
  1546.    appended anyway. The newline is stored in the pattern space as "\n"
  1547.    where it can be addressed by grouping "\(...\)" and moved in the
  1548.    RHS. Thus, to change the "twolines" example used earlier, the
  1549.    following script will work:
  1550.  
  1551.       sed '/twolines/{G;s/\(two\)\(lines\)\(\n\)/\1\3\2/;}'
  1552.  
  1553.    (e) Inserting full lines, not breaking lines up:
  1554.  
  1555.    If one is not *changing* lines but only inserting complete lines
  1556.    before or after a pattern, the procedure is much easier. Use the
  1557.    "i" (insert) or "a" (append) command, making the alterations by an
  1558.    external script. To insert "This line is new" BEFORE each line
  1559.    matching a regex:
  1560.  
  1561.       /RE/i This line is new               # HHsed, sedmod, gsed 3.02a
  1562.       /RE/{x;s/.*/This line is new/;G;}    # other seds
  1563.  
  1564.    To append "This line is new" AFTER each line matching a regex:
  1565.  
  1566.       /RE/a This line is new               # HHsed, sedmod, gsed 3.02a
  1567.       /RE/{G;s/$/This line is new/;}       # other seds
  1568.  
  1569.    To append 2 blank lines after each line matching a regex:
  1570.  
  1571.       /RE/{G;G;}                    # assumes the hold space is empty
  1572.  
  1573.    To replace each line matching a regex with 5 blank lines:
  1574.  
  1575.       /RE/{s/.*//;G;G;G;G;}         # assumes the hold space is empty
  1576.  
  1577.    (f) Use the "y///" command if possible:
  1578.  
  1579.    On some Unix versions of sed (not GNU sed!), though the s///
  1580.    command won't accept '\n' in the RHS, the y/// command does. If
  1581.    your Unix sed supports it, a newline after "aaa" can be inserted
  1582.    this way (which is not portable to GNU sed or other seds):
  1583.  
  1584.       s/aaa/&~/; y/~/\n/;    # assuming no other '~' is on the line!
  1585.  
  1586. 4.7. How do I represent control-codes or nonprintable characters?
  1587.  
  1588.    GNU sed v3.02.80, GNU sed v1.03, and HHsed v1.5 by Howard Helman
  1589.    all support all support the notation \xNN, where "NN" are two valid
  1590.    hex numbers, 00-FF.
  1591.  
  1592.    sed is not intended to process binary or object code, and files
  1593.    which contain nulls (0x00) will usually generate errors in most
  1594.    versions of sed (GNU sed 3.02a is an exception; it allows nulls in
  1595.    the input files and also in regexes).
  1596.  
  1597.    On Unix platforms, the 'echo' command may allow insertion of octal
  1598.    or hex values, e.g., `echo "\0nnn"` or `echo -n "\0nnn"`. The echo
  1599.    command may also support syntax like '\\b' or '\\t' for backspace
  1600.    or tab characters. Check the man pages to see what syntax your
  1601.    version of echo supports. Some versions support the following:
  1602.  
  1603.       # replace 0x1A (32 octal) with ASCII letters
  1604.       sed 's/'`echo "\032"`'/Ctrl-Z/g'
  1605.  
  1606.       # note the 3 backslashes in the command below
  1607.       sed "s/.`echo \\\b`//g"
  1608.  
  1609. 4.8. How do I read environment variables with sed?
  1610.  
  1611. 4.8.1. - on Unix platforms
  1612.  
  1613.    In Unix, environment variables are words which begin with a dollar
  1614.    sign, such as $TERM, $HOME, $user, or $path.  In sed, the dollar
  1615.    sign is used to indicate the last line of the input file, the end
  1616.    of a line (in the LHS), or a literal symbol (in the RHS). Sed
  1617.    cannot access variables directly, so one must pay attention to
  1618.    shell quoting requirements to expand the variables properly.
  1619.  
  1620.    To ALLOW the Unix shell to interpret the dollar sign (replacing it
  1621.    with an environment variable), put the script in double quotes:
  1622.  
  1623.       sed "s/_terminal-type_/$TERM/g" input.file >output.file
  1624.  
  1625.    To PREVENT the Unix shell from interpreting the dollar sign
  1626.    (letting sed define its meaning), put the script in single quotes:
  1627.  
  1628.       sed 's/.$//' DOS.file >Unix.file
  1629.  
  1630.    To use BOTH Unix $environment_vars and sed /end-of-line$/ pattern
  1631.    matching, use single quotes to bracket the sed part 'like so', then
  1632.    follow immediately with double quotes "$HERE" when you want the
  1633.    shell to substitute the variable, and resume with single quotes
  1634.    again where 'sed should set the meaning'. There must be NO SPACE
  1635.    between the closing single quotes and the opening double quotes. To
  1636.    demonstrate with the example two sentences above:
  1637.  
  1638.       sed 'like so'"$HERE"'sed should set the meaning'  # rough idea
  1639.       sed "s/$user"'$/root/' input.file >output.file    # sample use
  1640.  
  1641.    In the sample use above, we search for the user's name (which is
  1642.    stored as an environment variable) when it occurs at the end of the
  1643.    line ($), and we substitute the word "root" in all these occasions.
  1644.  
  1645.    In writing shell scripts, we likewise begin with single quote marks
  1646.    ('), close them upon encountering the variable, enclose the
  1647.    variable name in double quotes ("), and resume with single quotes,
  1648.    closing them at the end of the sed script.  Example:
  1649.  
  1650.       #! /bin/sh
  1651.       # lower to upper, that could be changed
  1652.       FROM='abcdefgh'
  1653.       TO='ABCDEFGH'
  1654.       ... misc commands that pipe data into a longer sed script.
  1655.       sed '
  1656.       ...
  1657.       # do the conversion
  1658.       y/'"$FROM"'/'"$TO"'/
  1659.       # some more commands go here . . .
  1660.       # last line is a single quote mark
  1661.       '
  1662.  
  1663.    Thus, each variable named $FROM is replaced by $TO, and the single
  1664.    quotes are used to glue the multiple lines together in the script.
  1665.    (See also section 4.10, "How do I handle shell quoting in sed?")
  1666.  
  1667. 4.8.2. - on MS-DOS and 4DOS platforms
  1668.  
  1669.    Under 4DOS and MS-DOS version 7.0 (Win95) or 7.10 (Win95 OSR2),
  1670.    environment variables can be accessed from the command prompt.
  1671.    Under MS-DOS 6.22 and below, environment variables can only be
  1672.    accessed from within batch files. Environment variables should be
  1673.    enclosed between percent signs and are case-insensitive; i.e.,
  1674.    %USER% or %user% will display the USER variable. To generate a true
  1675.    percent sign, just enter it twice.
  1676.  
  1677.    DOS versions of sed require that sed scripts be enclosed by double
  1678.    quote marks "..." (not single quotes!) if the script contains
  1679.    embedded tabs, spaces, redirection arrows or the vertical bar. In
  1680.    fact, if the input for sed comes from piping, a sed script should
  1681.    not contain a vertical bar, even if it is protected by double
  1682.    quotes (this seems to be bug in the normal MS-DOS syntax). Thus,
  1683.  
  1684.       echo blurk | sed "s/^/ |foo /"     # will cause an error
  1685.       sed "s/^/ |foo /" blurk.txt        # will work as expected
  1686.  
  1687.    Using DOS environment variables which contain DOS path statements
  1688.    (such as a TMP variable set to "C:\TEMP") within sed scripts is
  1689.    discouraged because sed will interpret the backslash '\' as a
  1690.    metacharacter to "quote" the next character, not as a normal
  1691.    symbol. Thus,
  1692.  
  1693.       sed "s/^/%TMP% /" somefile.txt
  1694.  
  1695.    will not prefix each line with (say) "C:\TEMP ", but will prefix
  1696.    each line with "C:TEMP "; sed will discard the backslash, which is
  1697.    probably not what you want. Other variables such as %PATH% and
  1698.    %COMSPEC% will also lose the backslash within sed scripts.
  1699.  
  1700.    Environment variables which do not use backslashes are usually
  1701.    workable. Thus, all the following should work without difficulty,
  1702.    if they are invoked from within DOS batch files:
  1703.  
  1704.       sed "s/=username=/%USER%/g" somefile.txt
  1705.       echo %FILENAME% | sed "s/\.TXT/.BAK/"
  1706.       grep -Ei "%string%" somefile.txt | sed "s/^/  /"
  1707.  
  1708.    while from either the DOS prompt or from within a batch file,
  1709.  
  1710.       sed "s/%%/ percent/g" input.fil >output.fil
  1711.  
  1712.    will replace each percent symbol in a file with " percent" (adding
  1713.    the leading space for readability).
  1714.  
  1715. 4.9. How do I export or pass variables back into the environment?
  1716.  
  1717. 4.9.1. - on Unix platforms
  1718.  
  1719.    Suppose that line #1, word #2 of the file 'terminals' contains a
  1720.    value to be put in your TERM environment variable. Sed cannot
  1721.    export variables directly to the shell, but it can pass strings to
  1722.    shell commands. To set a variable in the Bourne shell:
  1723.  
  1724.       TERM=`sed 's/^[^ ][^ ]* \([^ ][^ ]*\).*/\1/;q' terminals`;
  1725.       export TERM
  1726.  
  1727.    If the second word were "Wyse50", this would send the shell command
  1728.    "TERM=Wyse50".
  1729.  
  1730. 4.9.2. - on MS-DOS or 4DOS platforms
  1731.  
  1732.    Sed cannot directly manipulate the environment. Under DOS, only
  1733.    batch files (.BAT) can do this, using the SET instruction, since
  1734.    they are run directly by the command shell. Under 4DOS, special
  1735.    4DOS commands (such as ESET) can also alter the environment.
  1736.  
  1737.    Under DOS or 4DOS, sed can select a word and pass it to the SET
  1738.    command. Suppose you want the 1st word of the 2nd line of MY.DAT
  1739.    put into an environment variable named %PHONE%. You might do this:
  1740.  
  1741.       @echo off
  1742.       sed -n "2 s/^\([^ ][^ ]*\) .*/SET PHONE=\1/p;3q" MY.DAT > GO_.BAT
  1743.       call GO_.BAT
  1744.       echo The environment variable for PHONE is %PHONE%
  1745.       :: cleanup
  1746.       del GO_.BAT
  1747.  
  1748.    The sed script assumes that the first character on the 2nd line is
  1749.    not a space and uses grouping \(...\) to save the first string of
  1750.    non-space characters as \1 for the RHS. In writing any batch files,
  1751.    make sure that output filenames such as GO_.BAT don't overwrite
  1752.    preexisting files of the same name.
  1753.  
  1754. 4.10. How do I handle Unix shell quoting in sed?
  1755.  
  1756.    To embed a literal single quote (') in a script, use (a) or (b):
  1757.  
  1758.    (a) If possible, put the script in double quotes:
  1759.  
  1760.       sed "s/cannot/can't/g" file
  1761.  
  1762.    (b) If the script must use single quotes, then close-single-quote
  1763.    the script just before the SPECIAL single quote, prefix the single
  1764.    quote with a backslash, and use a 2nd pair of single quotes to
  1765.    finish marking the script. Thus:
  1766.  
  1767.       sed 's/cannot$/can'\''t/g' file
  1768.  
  1769.    Though this looks hard to read, it breaks down to 3 parts:
  1770.  
  1771.       's/cannot$/can'   \'   't/g'
  1772.       ---------------   --   -----
  1773.  
  1774.    To embed a literal double quote (") in a script, use (a) or (b):
  1775.  
  1776.    (a) If possible, put the script in single quotes. You don't need to
  1777.    prefix the double quotes with anything. Thus:
  1778.  
  1779.       sed 's/14"/fourteen inches/g' file
  1780.  
  1781.    (b) If the script must use double quotes, then prefix the SPECIAL
  1782.    double quote with a backslash (\). Thus,
  1783.  
  1784.       sed "s/$length\"/$length inches/g" file
  1785.  
  1786.    To embed a literal backslash (\) into a script, enter it twice:
  1787.  
  1788.       sed 's/C:\\DOS/D:\\DOS/g' config.sys
  1789.  
  1790. 4.11. How do I delete a block of text if the block contains a certain
  1791.       regular expression?
  1792.  
  1793.    The following deletes the block between 'start' and 'end'
  1794.    inclusively, if and only if the block contains the string
  1795.    (optionally a pattern) 'regex'. Written by Russell Davies
  1796.    <r@itntl.bhp.com.au>, with comments by the FAQ maintainer:
  1797.  
  1798.       :t
  1799.       /start/,/end/ {    # For each line between these block markers..
  1800.          /end/!{         #   If we are not at the /end/ marker
  1801.             $!{          #     nor the last line of the file,                 |
  1802.                N;        #     add the Next line to the pattern space
  1803.                bt
  1804.             }            #   and branch (loop back) to the :t label.
  1805.          }               # This line matches the /end/ marker.                |
  1806.          /regex/d;       # If /regex/ matches, delete the block.              |
  1807.       }                  # Otherwise, the block will be printed.
  1808.  
  1809. 4.12. How do I locate/print a paragraph of text if the paragraph
  1810.       contains a certain regular expression?
  1811.  
  1812.    Assume that paragraphs are separated by blank lines. For regexes
  1813.    that are single terms, use the following script:
  1814.  
  1815.       sed -e '/./{H;$!d;}' -e 'x;/regex/!d'
  1816.  
  1817.    To print paragraphs only if they contain 3 specific regular
  1818.    expressions (RE1, RE2, and RE3), in any order in the paragraph:
  1819.  
  1820.       sed -e '/./{H;$!d;}' -e 'x;/RE1/!d;/RE2/!d;/RE3/!d'
  1821.  
  1822.    With this solution and the preceding one, if the paragraphs are
  1823.    excessively long (more than 4k in length), you may overflow sed's
  1824.    internal buffers. If using HHsed, you must add a "G;" command
  1825.    immediately after the "x;" in the scripts above to defeat a bug
  1826.    in HHsed (see section 6.7.F(5), below, for a description).
  1827.  
  1828. 4.13. How do I delete a block of _specific_ consecutive lines?
  1829.  
  1830.    If the block of lines always looks like this (with '^' and '$'
  1831.    representing the beginning and end of line, respectively):
  1832.  
  1833.       ^able$
  1834.       ^baker$
  1835.       ^charlie$
  1836.       ^delta$
  1837.  
  1838.    and if there is never any deviation from this format (e.g., "able"
  1839.    *always* is followed by "baker", etc.), this will work fine:
  1840.  
  1841.       sed '/^able$/,/^delta$/d' files    # most seds
  1842.       sed '/^able$/,+3d' files           # HHsed, sedmod, gsed 3.02.80
  1843.  
  1844.    However, if the top line sometimes appears alone or is followed by
  1845.    other lines, if the block may have additional lines in the middle,
  1846.    or if a partial block could possibly occur somewhere in the file, a
  1847.    more explicit script is needed.
  1848.  
  1849.    The following scripts show how to delete blocks of specific
  1850.    consecutive lines. Only an exact match of the block is deleted, and
  1851.    partial matches of the block are left alone.
  1852.  
  1853.       # sed script to delete 2 consecutive lines: /^RE1\nRE2$/
  1854.       $b
  1855.       /^RE1$/ {
  1856.         $!N
  1857.         /^RE1\nRE2$/d
  1858.         P;D
  1859.       }
  1860.       #---end of script---
  1861.  
  1862.  
  1863.       # sed script to delete 3 consecutive lines. (This script
  1864.       # fails under GNU sed earlier than version 3.02.)
  1865.       : more
  1866.       $!N
  1867.       s/\n/&/2;
  1868.       t enough
  1869.       $!b more
  1870.       : enough
  1871.       /^RE1\nRE2\nRE3$/d
  1872.       P;D
  1873.       #---end of script---
  1874.  
  1875.    For example, to delete a block of 5 consecutive lines, the previous
  1876.    script must be altered in only two places:
  1877.  
  1878.    (1) Change the 2 in "s/\n/&/2;" to a 4 (the trailing semicolon is
  1879.    needed to work around a bug in HHsed v1.5).
  1880.  
  1881.    (2) Change the regex line to "/^RE1\nRE2\nRE3\nRE4\nRE5$/d",
  1882.    modifying the expression as needed.
  1883.  
  1884.    Suppose we want to delete a block of two blank lines followed by
  1885.    the word "foo" followed by another blank line (4 lines in all).
  1886.    Other blank lines and other instances of "foo" should be left
  1887.    alone. After changing the '2' to a '3' (always one number less than
  1888.    the total number of lines), the regex line would look like this:
  1889.    "/^\n\nfoo\n$/d". (Thanks to Greg Ubben for this script.)
  1890.  
  1891.    As an alternative for older versions of GNU sed, the following
  1892.    script will delete 4 consecutive lines:
  1893.  
  1894.       # sed script to delete 4 consecutive lines (gsed-2.05 and below)
  1895.       /^RE1$/!b
  1896.       $!N
  1897.       $!N
  1898.       :a
  1899.       $b
  1900.       N
  1901.       /^RE1\nRE2\nRE3\nRE4$/d
  1902.       P
  1903.       s/^.*\n\(.*\n.*\n.*\)$/\1/
  1904.       ba
  1905.       #---end of script---
  1906.  
  1907.    Its drawback is that it must be modified in 3 places instead of 2
  1908.    to adapt it for more lines, and as additional lines are added, the
  1909.    's' command is forced to work harder to match the regexes. On the
  1910.    other hand, it avoids a problem with gsed-2.05 and shows another
  1911.    way to solve the problem of deleting consecutive lines.
  1912.  
  1913. 4.14. How do I read (insert/add) a file at the top of a textfile?
  1914.  
  1915.    Given a textfile, file1, one may wish to prepend or insert an
  1916.    external file, fileT, to the top of it before processing the file.
  1917.    Normally, this should be done from the Unix or DOS shell before
  1918.    passing file1 on to sed (MS-DOS 5.0 or lower needs 3 commands to do
  1919.    this; for DOS 6.0 or higher, the MOVE command is available):
  1920.  
  1921.       copy fileT+file1 temp                   # MS-DOS command 1
  1922.       echo Y | copy temp file1                # MS-DOS command 2
  1923.       del temp                                # MS-DOS command 3
  1924.       cat fileT file1 >temp; mv temp file1    # Unix commands
  1925.  
  1926.    However, if inserting the file must be done from within sed, there
  1927.    is a way. The expected sed command "1 r fileT" will not work; it
  1928.    first prints line 1 and then inserts fileT between lines 1 and 2.
  1929.    The following two-line sed script solves this problem, although
  1930.    there must be at least 2 lines in file1 for the script to work
  1931.    properly:
  1932.  
  1933.       1{ h; r fileT; D; }
  1934.       2{ x; G; }
  1935.  
  1936. 4.15. How do I address all the lines between RE1 and RE2, excluding
  1937.       the lines themselves?
  1938.  
  1939.    Normally, to address the lines between two regular expressions, RE1
  1940.    and RE2, one would do this: '/RE1/,/RE2/{commands;}'. Excluding
  1941.    those lines takes an extra step. To put 2 arrows before each line
  1942.    between RE1 and RE2, except for those lines:
  1943.  
  1944.       sed '1,/RE1/!{ /RE2/,/RE1/!s/^/>>/; }' input.fil
  1945.  
  1946.    The preceding script, though short, may be difficult to follow. It
  1947.    also requires that /RE1/ cannot occur on the first line of the
  1948.    input file. The following script, though it's not a one-liner, is
  1949.    easier to read and it permits /RE1/ to appear on the first line:
  1950.  
  1951.       /RE1/,/RE2/{
  1952.         /RE1/b
  1953.         /RE2/b
  1954.         s/^/>>/
  1955.       }
  1956.  
  1957.    Contents of input.fil:         Output of sed script:
  1958.       aaa                           aaa
  1959.       bbb                           bbb
  1960.       RE1                           RE1
  1961.       aaa                           >>aaa
  1962.       bbb                           >>bbb
  1963.       ccc                           >>ccc
  1964.       RE2                           RE2
  1965.       end                           end
  1966.  
  1967. 4.16. How do I replace "/some/UNIX/path" in a substitution?
  1968.  
  1969.    Technically, the normal meaning of the slash can be disabled by
  1970.    prefixing it with a backslash. Thus,
  1971.  
  1972.       sed 's/\/some\/UNIX\/path/\/a\/new\/path/g' files
  1973.  
  1974.    But this is hard to read and write. There is a better solution.
  1975.    The s/// substitution command allows '/' to be replaced by any
  1976.    other character (including spaces or alphanumerics). Thus,
  1977.  
  1978.       sed 's|/some/UNIX/path|/a/new/path|g' files
  1979.  
  1980.    and if you are using variable names in a Unix shell script,
  1981.  
  1982.       sed "s|$OLDPATH|$NEWPATH|g" oldfile >newfile
  1983.  
  1984. 4.17. How do I replace "C:\SOME\DOS\PATH" in a substitution?
  1985.  
  1986.    For MS-DOS users, every backslash must be doubled. Thus, to replace
  1987.    "C:\SOME\DOS\PATH" with "D:\MY\NEW\PATH" --
  1988.  
  1989.       sed "s|C:\\SOME\\DOS\\PATH|D:\\MY\\NEW\\PATH|g" infile >outfile
  1990.  
  1991.    Remember that DOS pathnames are not case sensitive and can appear
  1992.    in upper or lower case in the input file. If this concerns you, use
  1993.    gsed v3.02 with the "i" flag or sedmod with the -i switch to ignore
  1994.    case on the LHS:
  1995.  
  1996.       @echo off
  1997.       :: sample MS-DOS batch file to alter path statements
  1998.       set old=C:\\SOME\\DOS\\PATH
  1999.       set new=D:\\MY\\NEW\\PATH
  2000.       gsed "s|%old%|%new%|gi" infile >outfile
  2001.       :: or
  2002.       ::     sedmod -i "s|%old%|%new%|g" infile >outfile
  2003.       set old=
  2004.       set new=
  2005.  
  2006.    Also, remember that under Win95 long filenames may be stored in two
  2007.    formats: e.g., as "C:\Program Files" or as "C:\PROGRA~1".
  2008.  
  2009. 4.18. How do I convert files with toggle characters, like +this+, to
  2010.       look like [i]this[/i]?
  2011.  
  2012.    Input files, especially message-oriented text files, often contain
  2013.    toggle characters for emphasis, like ~this~, *this*, or =this=. Sed
  2014.    can make the same input pattern produce alternating output each
  2015.    time it is encountered. Typical needs might be to generate HMTL
  2016.    codes or print codes for boldface, italic, or underscore. This
  2017.    script accomodates multiple occurrences of the toggle pattern on
  2018.    the same line, as well as cases where the pattern starts on one
  2019.    line and finishes several lines later, even at the end of the file:
  2020.  
  2021.       # sed script to convert +this+ to [i]this[/i]
  2022.       :a
  2023.       /+/{ x;        # If "+" is found, switch hold and pattern space
  2024.         /^ON/{       # If "ON" is in the (former) hold space, then ..
  2025.           s///;      # .. delete it
  2026.           x;         # .. switch hold space and pattern space back
  2027.           s|+|[/i]|; # .. turn the next "+" into "[/i]"
  2028.           ba;        # .. jump back to label :a and start over
  2029.         }
  2030.       s/^/ON/;       # Else, "ON" was not in the hold space; create it
  2031.       x;             # Switch hold space and pattern space
  2032.       s|+|[i]|;      # Turn the first "+" into "[i]"
  2033.       ba;            # Branch to label :a to find another pattern
  2034.       }
  2035.       #---end of script---
  2036.  
  2037.    This script uses the hold space to create a "flag" to indicate
  2038.    whether the toggle is ON or not. We have added remarks to
  2039.    illustrate the script logic, but in most versions of sed remarks
  2040.    are not permitted after 'b'ranch commands or labels.
  2041.  
  2042.    If you are sure that the +toggle+ characters never cross line
  2043.    boundaries (i.e., never begin on one line and end on another), this
  2044.    script can be reduced to one line:
  2045.  
  2046.       s|+\([^+][^+]*\)+|[i]\1[/i]|g
  2047.  
  2048.    If your toggle pattern contains regex metacharacters (such as * and
  2049.    +, in the case of HHsed), remember to quote them with backslashes.
  2050.  
  2051. 4.19. How do I delete only the first occurrence of a pattern?
  2052.  
  2053.    To delete only the first line that contains the pattern RE, where
  2054.    "RE" is any regular expression, but leave all other lines
  2055.    containing RE alone, do this:
  2056.  
  2057.       gsed '0,/RE/{//d}' file                     # GNU sed 3.02.80
  2058.       sed '/RE/{x;/Y/!{s/^/Y/;h;d;};x;}' file     # other seds
  2059.  
  2060.    And if you *know* the pattern will not occur on line 1 and you
  2061.    don't use GNU sed, this will work:
  2062.  
  2063.       sed '1,/RE/{/RE/d;}' file
  2064.  
  2065. 4.20. How do I commify a string of numbers?
  2066.  
  2067.    Use the simplest script necessary to accomplish your task. As
  2068.    variations of the line increase, the sed script must become more
  2069.    complex to handle additional conditions. Whole numbers are
  2070.    simplest, followed by decimal formats, followed by embedded words.
  2071.  
  2072.    Case 1: simple strings of whole numbers separated by spaces or
  2073.    commas, with an optional negative sign. To convert this:
  2074.  
  2075.       4381, -1222333, and 70000: - 44555666 1234567890 words
  2076.       56890  -234567, and 89222  -999777  345888777666 chars
  2077.  
  2078.    to this:
  2079.  
  2080.       4,381, -1,222,333, and 70,000: - 44,555,666 1,234,567,890 words
  2081.       56,890  -234,567, and 89,222  -999,777  345,888,777,666 chars
  2082.  
  2083.    use one of these one-liners:
  2084.  
  2085.       sed ':a;s/\B[0-9]\{3\}\>/,&/;ta'                      # GNU sed
  2086.       sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta'  # other seds
  2087.  
  2088.    Case 2: strings of numbers which may have an embedded decimal
  2089.    point, separated by spaces or commas, with an optional negative
  2090.    sign. To change this:
  2091.  
  2092.       4381,  -6555.1212 and 70000,  7.18281828  44906982.071902
  2093.       56890   -2345.7778 and 8.0000:  -49000000 -1234567.89012
  2094.  
  2095.    to this:
  2096.  
  2097.       4,381,  -6,555.1212 and 70,000,  7.18281828  44,906,982.071902
  2098.       56,890   -2,345.7778 and 8.0000:  -49,000,000 -1,234,567.89012
  2099.  
  2100.    use the following command for GNU sed:
  2101.  
  2102.       sed ':a;s/\(^\|[^0-9.]\)\([0-9]\+\)\([0-9]\{3\}\)/\1\2,\3/g;ta'
  2103.  
  2104.    and for other versions of sed:
  2105.  
  2106.       sed -f case2.sed files
  2107.  
  2108.       # case2.sed
  2109.       s/^/ /;                 # add space to start of line
  2110.       :a
  2111.       s/\( [-0-9]\{1,\}\)\([0-9]\{3\}\)/\1,\2/g
  2112.       ta
  2113.       s/ //;                  # remove space from start of line
  2114.       #---end of script---
  2115.  
  2116. ------------------------------
  2117.  
  2118. 5. WHY ISN'T THIS WORKING?
  2119.  
  2120. 5.1. Why don't my variables like $var get expanded in my sed script?
  2121.  
  2122.    Because your sed script uses 'single quotes' instead of "double
  2123.    quotes". Unix shells never expand $variables in single quotes.
  2124.  
  2125.    This is probably the most frequently-asked sed question. For more
  2126.    info on using variables, see section 4.8.
  2127.  
  2128. 5.2. I'm using 'p' to print, but I have duplicate lines sometimes.
  2129.  
  2130.    Sed prints the entire file by default, so the 'p' command might
  2131.    cause the duplicate lines. If you want the whole file printed,
  2132.    try removing the 'p' from commands like 's/foo/bar/p'. If you want
  2133.    part of the file printed, run your sed script with -n flag to
  2134.    suppress normal output, and rewrite the script to get all output
  2135.    from the 'p' comand.
  2136.  
  2137.    If you're still getting duplicate lines, you are probably finding
  2138.    several matches for the same line. Suppose you want to print lines
  2139.    with the words "Peter" or "James" or "John", but not the same line
  2140.    twice. The following command will fail:
  2141.  
  2142.       sed -n '/Peter/p; /James/p; /John/p' files
  2143.  
  2144.    Since all 3 commands of the script are executed for each line,
  2145.    you'll get extra lines. A better way is to use the 'd' (delete) or
  2146.    'b' (branch) commands, like so (with GNU sed):
  2147.  
  2148.       sed '/Peter/b; /James/b; /John/b; d' files          # one way
  2149.       sed -n '/Peter/{p;d;};/James/{p;d;};/John/p' files  # a 2nd way
  2150.       sed -n '/Peter/{p;b;};/James/{p;b;};/John/p' files  # a 3rd way
  2151.       sed '/Peter\|James\|John/!d' files                  # best way :-)
  2152.  
  2153.    On standard seds, these must be broken down with -e commands:
  2154.  
  2155.       sed -e '/Peter/b' -e '/James/b' -e '/John/b' -e d files
  2156.       sed -n -e '/Peter/{p;d;}' -e '/James/{p;d;}' -e '/John/p' files
  2157.  
  2158.    The 3rd line would require too many -e commands to fit on one line,
  2159.    since standard versions of sed require an -e command after each 'b'
  2160.    and also after each closing brace '}'.
  2161.  
  2162. 5.3. Why does my DOS version of sed process a file part-way through
  2163.      and then quit?
  2164.  
  2165.    First, look for errors in the script. Have you used the -n switch
  2166.    without telling sed to print anything to the console?  Have you
  2167.    read the docs to your version of sed to see if it has switches or a
  2168.    syntax you may have misused? If you are sure your sed script is
  2169.    valid, a probable cause is an end-of-file (EOF) marker embedded in
  2170.    the file. An EOF marker (a/k/a SUB) is a Control-Z character, with
  2171.    the values of 1A hex or 026 decimal. As soon as any DOS version of
  2172.    sed encounters a Ctrl-Z character, sed stops processing.
  2173.  
  2174.    To locate the EOF character, use Vern Buerg's shareware file viewer
  2175.    LIST.COM <http://www.buerg.com/list.html>. In text mode, look for a
  2176.    right-arrow symbol; in hex mode (Alt-H), look for a 1A code. With
  2177.    Unix utilities ported to DOS, use 'od' (octal dump) to display
  2178.    hexcodes in your file, and then use sed to locate the offending
  2179.    character:
  2180.  
  2181.       od -txC badfile.txt | sed -n "/ 1a /p; / 1a$/p"
  2182.  
  2183.    Then edit the input file to remove the offending character(s).
  2184.  
  2185.    If you would rather NOT edit the input file, there is still a fix.
  2186.    It requires the DJGPP 32-bit port of 'tr', the Unix translate
  2187.    program, ver 1.22. This version is included as one of the GNU text
  2188.    utilities, available at
  2189.       http://www.simtel.net/pub/simtelnet/gnu/djgpp/v2gnu/txt122b.zip
  2190.    It is important to get the DJGPP version of 'tr' because other
  2191.    versions ported to DOS will stop processing when they encounter the
  2192.    EOF character. Use the -d (delete) command:
  2193.  
  2194.       tr -d \32 < badfile.txt | sed -f myscript.sed
  2195.  
  2196. 5.4. My RE isn't matching/deleting what I want it to. (Or, "Greedy vs.
  2197.      stingy pattern matching")
  2198.  
  2199.    The two most common causes for this problem are: (1) misusing the
  2200.    '.' metacharacter, and (2) misusing the '*' metacharacter. The RE
  2201.    '.*' is designed to be "greedy" (i.e., matching as many characters
  2202.    as possible). However, sometimes users need an expression which is
  2203.    "stingy," matching the shortest possible string.
  2204.  
  2205.    (1) On single-line patterns, the '.' metacharacter matches any
  2206.    single character on the line. ('.' cannot match the newline at the
  2207.    end of the line because the newline is removed when the line is put
  2208.    into the pattern space; sed adds a newline automatically when the
  2209.    pattern space is printed.) On multi-line patterns obtained with the
  2210.    'N' or 'G' commands, '.' _will_ match a newline in the middle of the
  2211.    pattern space. If there are 3 lines in the pattern space, "s/.*//"
  2212.    will delete all 3 lines, not just the first one (leaving 1 blank
  2213.    line, since the trailing newline is added to the output).
  2214.  
  2215.    Normal misuse of '.' occurs in trying to match a word or bounded
  2216.    field, and forgetting that '.' will also cross the field limits.
  2217.    Suppose you want to delete the first word in braces:
  2218.  
  2219.       echo {one} {two} {three} | sed 's/{.*}/{}/'       # fails
  2220.       echo {one} {two} {three} | sed 's/{[^}]*}/{}/'    # succeeds
  2221.  
  2222.    's/{.*}/{}/' is not the solution, since the regex '.' will match
  2223.    any character, including the close braces. Replace the '.' with
  2224.    '[^}]', which signifies a negated character set '[^...]' containing
  2225.    anything other than a right brace. FWIW, we know that 's/{one}/{}/'
  2226.    would also solve our question, but we're trying to illustrate the
  2227.    use of the negated character set: [^anything-but-this].
  2228.  
  2229.    A negated character set should be used for matching words between
  2230.    quote marks, for fields separated by commas, etc. See also section
  2231.    4.5 ("How do I parse a comma-delimited data file?"), above.
  2232.  
  2233.    (2) The '*' metacharacter represents zero or more instances of the
  2234.    previous expression. The '*' metacharacter looks for the leftmost
  2235.    possible match first and will match zero characters. Thus,
  2236.  
  2237.       echo foo | sed 's/o*/EEE/'
  2238.  
  2239.    will generate 'EEEfoo', not 'fEEE' as one might expect. This is
  2240.    because /o*/ matches the null string at the beginning of the word.
  2241.  
  2242.    After finding the leftmost possible match, the '*' is GREEDY; it
  2243.    always tries to match the longest possible string. When two or
  2244.    three instances of '.*' occur in the same RE, the leftmost instance
  2245.    will grab the most characters. Consider this example, which uses
  2246.    grouping '\(...\)' to save patterns:
  2247.  
  2248.       echo bar bat bay bet bit | sed 's/^.*\(b.*\)/\1/'
  2249.  
  2250.    What will be displayed is 'bit', never anything longer, because
  2251.    the leftmost '.*' took the longest possible match. Remember this
  2252.    rule: "leftmost match, longest possible string, zero also matches."
  2253.  
  2254. 5.5. What is CSDPMI*B.ZIP and why do I need it?
  2255.  
  2256.    If you boot to MS-DOS instead of Windows and try to use GNU sed
  2257.    v1.18 or 3.02, you may encounter the following error message:
  2258.  
  2259.       no DPMI - Get csdpmi*b.zip
  2260.  
  2261.    "DPMI" stands for DOS Protected Mode Interface; it's basically a
  2262.    means of running DOS in Protected Mode (as opposed to Real Mode),
  2263.    which allows programs to share resources in extended memory without
  2264.    conflicting with one another. Running HIMEM.SYS and EMM386.EXE is
  2265.    not enough. The "CSDPMI*B.ZIP" refers to files written by Charles
  2266.    Sandmann to provide DPMI services for 32-bit computers (i.e.,
  2267.    386SX, 386DX, 486SX, etc.). Download this file:
  2268.  
  2269.       http://www.simtel.net/pub/simtelnet/gnu/djgpp/v2misc/csdpmi4b.zip
  2270.       ftp://ftp.cdrom.com/pub/simtelnet/gnu/djgpp/v2misc/csdpmi4b.zip
  2271.  
  2272.    and extract CWSDPMI.EXE, CWSDPR0.EXE and CWSPARAM.EXE from the ZIP
  2273.    file. Put all 3 CWS*.EXE files in the same directory as GSED.EXE
  2274.    and you're all set. There are DOC files enclosed, but they're
  2275.    nearly incomprehensible for the average computer user. (Another
  2276.    case of user-vicious documentation.)
  2277.  
  2278.    If you're running Windows and you normally use a DOS session to run
  2279.    GNU sed (i.e., you get to a DOS prompt with a resizable window or
  2280.    you press Alt-Enter to switch to full-screen mode), you don't need
  2281.    the CWS*.EXE files at all, since Windows uses DPMI already.
  2282.  
  2283. 5.6. Where are the man pages for GNU sed?
  2284.  
  2285.    Prior to GNU sed v3.02, there weren't any. Until recently, man
  2286.    pages distributed with gsed were borrowed from old sources or from
  2287.    other compilations. None of them were "official." Even the man and
  2288.    info pages distributed with gsed 3.02 are incomplete. For example,
  2289.    they omit special regexes recognized by GNU sed not in most seds;
  2290.    see section 6.8.3 ("Special syntax in REs"), below.
  2291.  
  2292. 5.7. How do I tell what version of sed I am using?
  2293.  
  2294.    Try entering "sed" all by itself on the command line, followed by
  2295.    no arguments or parameters.  Also, try "sed --version".  In a
  2296.    pinch, you can also try this:
  2297.  
  2298.       strings sed | grep -i ver
  2299.  
  2300.    Your version of 'strings' must be a version of the Unix utility of
  2301.    this name. It should not be the DOS utility STRINGS.COM by Douglas
  2302.    Boling.
  2303.  
  2304. 5.8. Does sed issue an exit code?
  2305.  
  2306.    Most versions of sed do not, but check the documentation that came
  2307.    with whichever version you are using. GNU sed issues an exit code
  2308.    of 0 if the program terminated normally, 1 if there were errors in
  2309.    the script, and 2 if there were errors during script execution.
  2310.  
  2311. 5.9. The 'r' command isn't inserting the file into the text.
  2312.  
  2313.    On most versions of sed (except HHsed and gsed-3.02), the 'r'
  2314.    (read) and 'w' (write) commands must be followed by exactly one
  2315.    space, then the filename, and then terminated by a newline. Any
  2316.    additional characters before or after the filename are interpreted
  2317.    as being part of the filename. Thus "/RE/r  insert.me" would try to
  2318.    locate a file called ' insert.me' (note the leading space!). If the
  2319.    file was not found, sed says nothing -- not even an error message.
  2320.  
  2321.    When sed scripts are used on the command line, every 'r' and 'w'
  2322.    must be the last command in that part of the script. Thus,
  2323.  
  2324.       sed -e '/regex/{r insert.file;d;}' source         # will fail           |
  2325.       sed -e '/regex/{r insert.file' -e 'd;}' source    # will succeed        |
  2326.  
  2327. 5.10. Why can't I match or delete a newline using the \n escape               |
  2328.       sequence? Why can't I match 2 or more lines using \n?                   |
  2329.  
  2330.    The \n will never match the newline at the end-of-line because the         |
  2331.    newline is always stripped off before the line is placed into the          |
  2332.    pattern space. To get 2 or more lines into the pattern space, use          |
  2333.    the 'N' command or something similar (such as 'H;...;g;').                 |
  2334.  
  2335.    Sed works like this: sed reads one line at a time, chops off the           |
  2336.    terminating newline, puts what is left into the pattern space where        |
  2337.    the sed script can address or change it, and when the pattern space        |
  2338.    is printed, appends a newline to stdout (or to a file). If the             |
  2339.    pattern space is entirely or partially deleted with 'd' or 'D', the        |
  2340.    newline is *not* added in such cases. Thus, scripts like                   |
  2341.  
  2342.       sed 's/\n//' file       # to delete newlines from each line             |
  2343.       sed 's/\n/foo\n/' file  # to add a word to the end of each line         |
  2344.  
  2345.    will NEVER work, because the trailing newline is removed _before_          |
  2346.    the line is put into the pattern space. To perform the above tasks,        |
  2347.    use one of these scripts instead:                                          |
  2348.  
  2349.       tr -d '\n' < file              # use tr to delete newlines              |
  2350.       sed ':a;N;$!ba;s/\n//g' file   # GNU sed to delete newlines             |
  2351.       sed 's/$/ foo/' file           # add "foo" to end of each line          |
  2352.  
  2353.    Since versions of sed other than GNU sed have limits to the size of        |
  2354.    the pattern buffer, the Unix 'tr' utility is to be preferred here.         |
  2355.    If the last line of the file contains a newline, GNU sed will add          |
  2356.    that newline to the output but delete all others, whereas tr will          |
  2357.    delete all newlines.                                                       |
  2358.    
  2359.    To match a block of two or more lines, there are 3 basic choices:          |
  2360.    (1) use the 'N' command to add the Next line to the pattern space;         |
  2361.    (2) use the 'H' command at least twice to append the current line          |
  2362.    to the Hold space, and then retrieve the lines from the hold space         |
  2363.    with x, g, or G; or (3) use address ranges (see section 3.3, above)        |
  2364.    to match lines between two specified addresses.                            |
  2365.    
  2366.    Choices (1) and (2) will put an \n into the pattern space, where it        |
  2367.    can be addressed as desired ('s/ABC\nXYZ/alphabet/g'). One example         |
  2368.    of using 'N' to delete a block of lines appears in section 4.13            |
  2369.    ("How do I delete a block of _specific_ consecutive lines?"). This         |
  2370.    example can be modified by changing the delete command to something        |
  2371.    else, like 'p' (print), 'i' (insert), 'c' (change), 'a' (append),          |
  2372.    or 's' (substitute).                                                       |
  2373.  
  2374.    Choice (3) will not put an \n into the pattern space, but it _does_        |
  2375.    match a block of consecutive lines, so it may be that you don't            |
  2376.    even need the \n to find what you're looking for. Since GNU sed            |
  2377.    version 3.02.80 now supports this syntax:                                  |
  2378.  
  2379.       sed '/start/,+4d'  # to delete "start" plus the next 4 lines,           |
  2380.  
  2381.    in addition to the traditional '/from here/,/to there/{...}' range         |
  2382.    addresses, it may be possible to avoid the use of \n entirely.             |
  2383.  
  2384. 5.11. My script aborts with an error message, "event not found".              |
  2385.  
  2386.    This error is generated by the csh or tcsh shells, not by sed. The         |
  2387.    exclamation mark (!) is special to csh/tcsh, and if you use it in          |
  2388.    command-line or shell scripts--even within single quotes--it must          |
  2389.    be preceded by a backslash. Thus, under the csh/tcsh shell:                |
  2390.  
  2391.       sed '/regex/!d'      # will fail                                        |
  2392.       sed '/regex/\!d'     # will succeed                                     |
  2393.    
  2394.    The exclamation mark should not be prefixed with a backslash when          |
  2395.    the script is called from a file, as "-f script.file".                     |
  2396.  
  2397. ------------------------------
  2398.  
  2399. 6. OTHER ISSUES
  2400.  
  2401. 6.1. I have a certain problem that stumps me. Where can I get help?
  2402.  
  2403.    Newsgroups:
  2404.  
  2405.       - alt.comp.editors.batch  (best choice)
  2406.       - comp.editors
  2407.       - comp.unix.questions
  2408.       - comp.unix.shell
  2409.  
  2410.    Send e-mail to:  owner-sed-users@jpusa.chi.il.us
  2411.  
  2412.    Your question will be posted on the "sed-users" mailing list, where
  2413.    many sed users will be able to see your question. Sending your
  2414.    question will not automatically subscribe you to the list.
  2415.  
  2416. 6.2. How does sed compare with awk, perl, and other utilities?
  2417.  
  2418.    Awk is a much richer language with many features of a programming
  2419.    language, including variable names, math functions, arrays, system
  2420.    calls, etc. Its command structure is similar to sed:
  2421.  
  2422.       address { command(s) }
  2423.  
  2424.    which means that for each line or range of lines that matches the
  2425.    address, execute the command(s). In both sed and awk, an address
  2426.    can be a line number or a RE somewhere on the line, or both.
  2427.  
  2428.    In program size, awk is 3-10 times larger than sed. Awk has most
  2429.    of the functions of sed, but not all. Notably, sed supports
  2430.    backreferences (\1, \2, ...) to previous expressions, and awk does
  2431.    not have any comparable function or syntax.
  2432.  
  2433.    Perl is a general-purpose programming language, with many features
  2434.    beyond text processing and interprocess communication, taking it
  2435.    well past awk or other scripting languages. Perl supports every
  2436.    feature sed does and has its own set of extended regular
  2437.    expressions, which give it extensive power in pattern matching and
  2438.    processing. (Note: the standard perl distribution comes with 's2p',
  2439.    a sed-to-perl conversion script. See section 3.6 for more info.)
  2440.    Like sed and awk, perl scripts do not need to be compiled into
  2441.    binary code. Like sed, perl can also run many useful "one-liners"
  2442.    from the command line, though with greater flexibility; see
  2443.    question 4.3 ("How do I make substitutions in every file in a
  2444.    directory, or in a complete directory tree?").
  2445.  
  2446.    On the other hand, the current version of perl is from 8 to 35
  2447.    times larger than sed in its executables alone (perl's library
  2448.    modules and allied files not included!). Further, for most simple
  2449.    tasks such as substitution, sed executes more quickly than either
  2450.    perl or awk. All these utilities serve to process input text,
  2451.    transforming it to meet our needs . . . or our arbitrary whims.
  2452.  
  2453. 6.3. When should I use sed?
  2454.  
  2455.    When you need a small, fast program to modify words, lines, or
  2456.    blocks of lines in a textfile.
  2457.  
  2458. 6.4. When should I NOT use sed?
  2459.  
  2460.    You should not use sed when you have "dedicated" tools which can do
  2461.    the job faster or with an easier syntax. Do not use sed when you
  2462.    only want to:
  2463.  
  2464.    - delete individual characters. Instead of "s/[abcd]//g", use
  2465.  
  2466.         tr -d "[a-d]"
  2467.  
  2468.    - squeeze sequential characters. Instead of "s/ee*/e/g", use
  2469.  
  2470.         tr -s "{character-set}"
  2471.  
  2472.    - change individual characters. Instead of "y/abcdef/ABCDEF/", use
  2473.  
  2474.         tr "[a-f]" "[A-F]"
  2475.  
  2476.    - print individual lines, based on patterns within the line itself.
  2477.      Instead, use "grep".
  2478.  
  2479.    - print blocks of lines, with 1 or more lines of context above
  2480.      and/or below a specific regular expression. Instead, use the GNU
  2481.      version of grep as follows:
  2482.  
  2483.         grep -A{number} -B{number}
  2484.  
  2485.    - remove individual lines, based on patterns within the line
  2486.      itself. Instead, use "grep -v".
  2487.  
  2488.    - print line numbers.  Instead, use "nl" or "cat -n".
  2489.  
  2490.    - reformat lines or paragraphs. Instead, use "fold", "fmt" or "par".
  2491.  
  2492.    Though sed can perfectly emulate certain functions of cat, grep,
  2493.    nl, rev, sort, tac, tail, tr, uniq, and other utilities, producing
  2494.    identical output, the native utilities are usually optimized to do
  2495.    the job more quickly than sed.
  2496.  
  2497. 6.5. When should I ignore sed and use Awk or Perl instead?
  2498.  
  2499.    If you can write the same script in Awk or Perl and do it in less
  2500.    time, then use Perl or Awk. There's no reason to spend an hour
  2501.    writing and debugging a sed script if you can do it in Perl in 10
  2502.    minutes (assuming that you know Perl already) and if the processing
  2503.    time or memory use is not a factor. Don't hunt pheasants with a .22
  2504.    if you have a shotgun at your side . . . unless you simply enjoy
  2505.    the challenge!
  2506.  
  2507.    Specifically, if you need to:
  2508.  
  2509.    - heavily comment what your scripts do. Use GNU sed, awk, or perl.
  2510.    - do case insensitive searching. Use gsed302, sedmod, awk or perl.
  2511.    - count fields (words) in a line. Use awk.
  2512.    - count lines in a block or objects in a file. Use awk.
  2513.    - check lengths of strings or do math operations. Use awk or perl.
  2514.    - handle very long lines or need very large buffers. Use gsed or perl.
  2515.    - handle binary data (control characters). Use perl (binmode).
  2516.    - loop through an array or list. Use awk or perl.
  2517.    - test for file existence, filesize, or fileage. Use perl or shell.
  2518.    - treat each paragraph as a line. Use awk or perl.
  2519.    - indicate /alternate|options/ in regexes. Use gsed, awk or perl.
  2520.    - use syntax like \xNN to match hex codes. Use gsed-3.02.80 or perl.
  2521.    - use (nested (regexes)) with backreferences. Use perl.
  2522.  
  2523.    Perl lovers: I know that perl can do everything awk can do, but
  2524.    please don't write me to complain. Why heft a shotgun when a .45
  2525.    will do? As we all know, "There is more than one way to do it."
  2526.  
  2527. 6.6. Known limitations among sed versions
  2528.  
  2529.    Limits on distributed versions, although source code for most
  2530.    versions of free sed allows for modification and recompilation.
  2531.    The term "no limit" when used below means there is no "fixed"
  2532.    limit. Limits are actually determined by one's hardware, memory,
  2533.    operating system, and which C library is used to compile sed.
  2534.  
  2535. 6.6.1. Maximum line length
  2536.  
  2537.       GNU sed 3.02: no limit
  2538.       GNU sed 2.05: no limit
  2539.       sedmod 1.0:   4096 bytes
  2540.       HHsed:        4000 bytes
  2541.  
  2542. 6.6.2. Maximum size for all buffers (pattern space + hold space)
  2543.  
  2544.       GNU sed 3.02: no limit
  2545.       GNU sed 2.05: no limit
  2546.       sedmod 1.0:   4096 bytes
  2547.       HHsed:        4000 bytes
  2548.  
  2549. 6.6.3. Maximum number of files that can be read with read command
  2550.  
  2551.       GNU sed 3.02: no limit
  2552.       GNU sed 2.05: total no. of r and w commands may not exceed 32
  2553.       sedmod 1.0:   total no. of r and w commands may not exceed 20
  2554.  
  2555. 6.6.4. Maximum number of files that can be written with 'w' command
  2556.  
  2557.       GNU sed 3.02: no limit (but typical Unix is 253)
  2558.       GNU sed 2.05: total no. of r and w commands may not exceed 32
  2559.       sedmod 1.0:   10
  2560.       HHsed:        10
  2561.  
  2562. 6.6.5. Limits on length of label names
  2563.  
  2564.       BSD sed:      8 characters
  2565.       GNU sed 3.02: no limit
  2566.       GNU sed 2.05: no limit
  2567.       HHsed:        no limit
  2568.  
  2569. 6.6.6. Limits on length of write-file names
  2570.  
  2571.       BSD sed:      40 characters
  2572.       GNU sed 3.02: no limit
  2573.       GNU sed 2.05: no limit
  2574.       HHsed:        no limit
  2575.  
  2576. 6.6.7. Limits on branch/jump commands
  2577.  
  2578.       HHsed:        50
  2579.  
  2580.    As a practical consequence, this means that HHsed will not read
  2581.    more than 50 lines into the pattern space via an N command, even if
  2582.    the pattern space is only a few hundred bytes in size. HHsed exits
  2583.    with an error message, "infinite branch loop at line {nn}".
  2584.  
  2585. 6.7. Known bugs among sed versions
  2586.  
  2587. A. GNU sed v3.02.80
  2588.  
  2589.    (1) N does not discard the contents of the pattern space upon              |
  2590.    reaching the end of file; not a bug. See section 6.8.6, below.             |
  2591.  
  2592. B. GNU sed v3.02
  2593.  
  2594.    (1) Affects only v3.02 binaries compiled with DJGPP for MS-DOS and
  2595.    MS-Windows: 'l' (list) command does not display a lone carriage
  2596.    return (0x0D, ^M) embedded in a line.
  2597.  
  2598.    (2) The expression "\<" causes problems when attempting the
  2599.    following types of substitutions, which should print "+aaa +bbb":
  2600.  
  2601.       echo aaa bbb | sed 's/\</+/g'    # prints "+a+a+a +b+b+b"
  2602.       echo aaa bbb | sed 's/\<./+&/g'  # prints "+a+a+a +b+b+b"
  2603.  
  2604.    (3) The N command no longer discards the contents of the pattern           |
  2605.    space upon reaching the end of file. This is not a bug, it's a             |
  2606.    feature. See section 6.8.6 "Commands which operate differently".           |
  2607.  
  2608. C. GNU sed v2.05
  2609.  
  2610.    (1) If a number follows the substitute command (e.g., s/f/F/10) and
  2611.    the number exceeds the possible matches on the pattern space, the
  2612.    command 't label' _always_ jumps to the specified label. 't' should
  2613.    jump only if the substitution was successful (or returned "true").
  2614.  
  2615.    (2) 'l' (list) command does not convert the following characters to
  2616.    hex values, but passes them through unchanged: 0xF7, 0xFB, 0xFC,
  2617.    0xFD, 0xFE.
  2618.  
  2619.    (3) A range address like "/foo/,14d" should delete every line from
  2620.    the first occurrence of "foo" until line 14, inclusive, and then if
  2621.    /foo/ occurs thereafter, delete only those lines. In gsed 2.05, if
  2622.    a second "foo" occurs in the file, that line and everything to the
  2623.    end of file will be deleted (since gsed is looking for line 14 to
  2624.    occur again!).
  2625.  
  2626.    (4) The regex /\'/ is not interpreted as an apostrophe or a single
  2627.    quote mark, as it should be. Instead, it is interpreted as $,
  2628.    representing the end-of-line! This can be proven by these tests:
  2629.  
  2630.       echo hello | gsed "/\'/d"        # entire line is deleted!
  2631.       echo hello | gsed "s/\'/YYY/"    # 'YYY' appended to string
  2632.  
  2633.    (5) Multiple occurrences of the 'w' command fail, as shown here,
  2634.    given that both "aaa" and "bbb" occur within the file:
  2635.  
  2636.       gsed -e "/aaa/w FILE" -e "/bbb/w FILE" input.txt
  2637.  
  2638.    (6) The expression "\<" causes problems when attempting the
  2639.    following type of substitution, which should print "+aaa +bbb":
  2640.  
  2641.       echo aaa bbb | sed 's/\</+/g'    # sed hangs up with no output
  2642.  
  2643.    The syntax 's/\<./+&/g' issues the proper output.
  2644.  
  2645. D. GNU sed v1.18
  2646.  
  2647.    (1) same as #1 for GNU sed v2.05, above.
  2648.  
  2649.    (2) The following command will lock the computer under Win95. Echos
  2650.    is an echo command that does not issue a trailing newline:
  2651.  
  2652.       echos any_word | gsed "s/[ ]*$//"
  2653.  
  2654.    (3) same as #3 for GNU sed v2.05, above.
  2655.  
  2656. E. GNU sed v1.03 (by Frank Whaley)
  2657.  
  2658.    (1) The \w and \W escape sequences both match only nonword
  2659.    characters. \w is misdefined and should match word characters.
  2660.  
  2661.    (2) The underscore is defined as a nonword character; it should be
  2662.    defined as a word character.
  2663.  
  2664.    (3) same as #3 for GNU sed v2.05, above.
  2665.  
  2666. F. HHsed v1.5 (by Howard Helman)
  2667.  
  2668.    (1) If a number follows the substitute command (e.g., s/foo/bar/2),
  2669.    in a sed script entered from the command line, two semicolons must
  2670.    follow the number, or they must be separated by an -e switch.
  2671.    Normally, only 1 semicolon is needed to separate commands.
  2672.  
  2673.       echo bit bet | HHsed "s/b/n/2;;s/b/B/"          # solution 1
  2674.       echo bit bet | HHsed -e "s/b/n/2" -e "s/b/B"    # solution 2
  2675.  
  2676.    (2) If the substitute command is followed by a number and a "p"
  2677.    flag, when the -n switch is used, the "p" flag must occur first.
  2678.  
  2679.       echo aaa | HHsed -n "s/./B/3p"    # bug! nothing prints
  2680.       echo aaa | HHsed -n "s/./B/p3"    # prints "aaB" as expected
  2681.  
  2682.    (3) The following commands will cause HHsed to lock the computer
  2683.    under MS-DOS or Win95. Note that they occur because of malformed
  2684.    regular expressions which will match no characters.
  2685.  
  2686.       sed -n "p;s/\<//g;" file
  2687.       sed -n "p;s/[char-set]*//g;" file
  2688.  
  2689.    (4) The range command '/RE1/,/RE2/' in HHsed will match one line if
  2690.    both regexes occur on the same line (see section 6.8.5, below).
  2691.    Though this could be construed as a feature, it should probably be
  2692.    considered a bug since its operation differs from every other
  2693.    version of sed. For example, '/----/,/----/{s/^/>>/;}' should put
  2694.    two angle brackets ">>" before every line which is sandwiched
  2695.    between a row of 4 or more hyphens. With HHsed, this command will
  2696.    only prefix the hyphens themselves with the angle brackets.
  2697.  
  2698.    (5) If the hold space is empty, the H command copies the pattern
  2699.    space to the hold space but fails to prepend a leading newline. The
  2700.    H command is supposed to add a newline, followed by the contents of
  2701.    the pattern space, to the hold space at all times. A workaround is
  2702.    "{G;s/^\(.*\)\(\n\)$/\2\1/;H;s/\n$//;}", but it requires knowing
  2703.    that the hold space is empty and using the command only once.
  2704.    Another alternative is to use the G or the A command alone at key
  2705.    points in the script.
  2706.  
  2707.    (6) If grouping is followed by an '*' or '+' operator, HHsed does
  2708.    not match the pattern, but issues no warning. See below:
  2709.  
  2710.       echo aaa | HHsed "/\(a\)*/d"      # nothing is deleted
  2711.       echo aaa | HHsed "/\(a\)+/d"      # nothing is deleted
  2712.       echo aaa | HHsed "s/\(a\)*/\1B/"  # nothing is changed
  2713.       echo aaa | HHsed "s/\(a\)+/\1B/"  # nothing is changed
  2714.  
  2715.    (7) If grouping is followed by an interval expression, HHsed halts
  2716.    with the error message "garbled command", in all of the following
  2717.    examples:
  2718.  
  2719.       echo aaa | HHsed "/\(a\)\{3\}/d"
  2720.       echo aaa | HHsed "/\(a\)\{1,5\}/d"
  2721.       echo aaa | HHsed "s/\(a\)\{3\}/\1B/"
  2722.  
  2723.    (8) In interval expressions, 0 is not supported. E.g., \{0,3\)
  2724.  
  2725. G. sedmod v1.0 (by Hern Chen)
  2726.  
  2727.    Technically, the following are limits (or features?) of sedmod, not
  2728.    bugs, since the docs for sedmod do not claim to support these
  2729.    missing features.
  2730.  
  2731.    (1) sedmod does not support standard range arguments \{...\}
  2732.    present in nearly all versions of sed.
  2733.  
  2734.    (2) If grouping is followed by an '*' or '+' operator, sedmod gives
  2735.    a "garbled command" message. However, if the grouped expressions
  2736.    are strings literals with no metacharacters, a partial workaround
  2737.    can be done like so:
  2738.  
  2739.       \(string\)\1*    # matches 1 or more instances of 'string'
  2740.       \(string\)\1+    # matches 2 or more instances of 'string'
  2741.  
  2742.    (3) sedmod does not support a numeric argument after the s///
  2743.    command, as in 's/a/b/3', present in nearly all versions of sed.
  2744.  
  2745.    The following are bugs in sedmod v1.0:
  2746.  
  2747.    (4) When the -i (ignore case) switch is used, the '/regex/d'
  2748.    command is not properly obeyed. Sedmod may miss one or more lines
  2749.    matching the expression, regardless of where they occur in the
  2750.    script. Workaround: use "/regex/{d;}" instead.
  2751.  
  2752. H. HP-UX sed
  2753.  
  2754.    (1) Versions of HP-UX sed up to and including version 10.20 are
  2755.    buggy. According to the README file, which comes with the GNU cc
  2756.    at <ftp://ftp.ntua.gr/pub/gnu/sed-2.05.bin.README>:
  2757.  
  2758.    "When building gcc on a hppa*-*-hpux10 platform, the `fixincludes'
  2759.    step (which involves running a sed script) fails because of a bug
  2760.    in the vendor's implementation of sed.  Currently the only known
  2761.    workaround is to install GNU sed before building gcc.  The file
  2762.    sed-2.05.bin.hpux10 is a precompiled binary for that platform."
  2763.  
  2764. I. SunOS 4.1 sed
  2765.  
  2766.    (1) Bug occurs in RE pattern matching when a non-null '[char-set]*'
  2767.    is followed by a null '\NUM' pattern recall, illustrated here and
  2768.    reported by Greg Ubben:
  2769.  
  2770.       s/\(a\)\(b*\)cd\1[0-9]*\2foo/bar/  # between '[0-9]*' and '\2'
  2771.       s/\(a\{0,1\}\).\{0,1\}\1/bar/      # between '.\{0,1\}' and '\1'
  2772.  
  2773.    Workaround: add a do-nothing 'X*' expression which will not match
  2774.    any characters on the line between the two components. E.g.,
  2775.  
  2776.       s/\(a\)\(b*\)cd\1[0-9]*X*\2foo/bar/
  2777.       s/\(a\{0,1\}\).\{0,1\}X*\1/bar/
  2778.  
  2779. J. SunOS 5.6 sed
  2780.  
  2781.    (1) If grouping is followed by an asterisk, SunOS sed does not match
  2782.    the null string, which it should do. The following command:
  2783.  
  2784.       echo foo | sed 's/f\(NO-MATCH\)*/g\1/'
  2785.  
  2786.    should transform "foo" to "goo" under normal versions of sed.
  2787.  
  2788. K. Ultrix 4.3 sed
  2789.  
  2790.    (1) If grouping is followed by an asterisk, Ultrix sed replies with
  2791.    "command garbled", as shown in the following example:
  2792.  
  2793.       echo foo | sed 's/f\(NO-MATCH\)*/g\1/'
  2794.  
  2795.    (2) If grouping is followed by a numeric operator such as \{0,9\},
  2796.    Ultrix sed does not find the match.
  2797.  
  2798. L. Digital Unix sed
  2799.  
  2800.    (1) The following comes from the man pages for sed distributed with
  2801.    new, 1998 versions of Digital Unix (reformatted to fit our
  2802.    margins):
  2803.  
  2804.    [Digital]  The h subcommand for sed does not work properly.  When
  2805.    you use the  h subcommand to place text into the hold area, only
  2806.    the last line of the specified text is saved.  You can use the H
  2807.    subcommand to append text to the hold area. The H subcommand and
  2808.    all others dealing with the hold area work correctly.
  2809.  
  2810.    (2) "$d" command issues an error message, "cannot parse".  Reported
  2811.    by Carlos Duarte on 8 June 1998.
  2812.  
  2813. 6.8. Known incompatibilities between sed versions
  2814.  
  2815. 6.8.1. Issuing commands from the command line
  2816.  
  2817.    Most versions of sed permit multiple commands to issued on the
  2818.    command line, separated by a semicolon (;). Thus,
  2819.  
  2820.       sed 'G;G' file
  2821.  
  2822.    should triple-space a file. However, certain commands REQUIRE
  2823.    separate expressions on the command line. These include:
  2824.  
  2825.       - all labels (':a', ':more', etc.)
  2826.       - all branching instructions ('b', 't')
  2827.       - commands to read and write files ('r' and 'w')
  2828.       - any closing brace, '}'
  2829.  
  2830.    If these commands are used, they must be the LAST commands of an
  2831.    expression. Subsequent commands must use another expression
  2832.    (another -e switch plus arguments).  E.g.,
  2833.  
  2834.       sed  -e :a -e 's/^.\{1,77\}$/ &/;ta' -e 's/\( *\)\1/\1/' files
  2835.  
  2836.    GNU sed and HHsed v1.5 allow these commands to be followed by a
  2837.    semicolon, and the previous script can be written like this:
  2838.  
  2839.       sed  ':a;s/^.\{1,77\}$/ &/;ta;s/\( *\)\1/\1/' files
  2840.  
  2841.    Versions differ in implementing the 'a' (append), 'c' (change), and
  2842.    'i' (insert) commands:
  2843.  
  2844.       sed "/foo/i New text here"              # HHsed/sedmod/gsed-30280
  2845.       gsed -e "/foo/i\\" -e "New text here"   # GNU sed
  2846.       sed1 -e "/foo/i" -e "New text here"     # one version of sed
  2847.       sed2 "/foo/i\ New text here"            # another version
  2848.  
  2849. 6.8.2. Using comments (prefixed by the '#' sign)
  2850.  
  2851.    Most versions of sed permit comments to appear in sed scripts only
  2852.    on the first line of the script. Comments on line 2 or thereafter
  2853.    are not recognized and will generate an error like "unrecognized
  2854.    command" or "command [bad-line-here] has trailing garbage".
  2855.  
  2856.    GNU sed, HHsed, sedmod, and HP-UX sed permit comments to appear on
  2857.    any line of the script, except after labels and branching commands
  2858.    (b,t), *provided* that a semicolon (;) occurs after the command
  2859.    itself. This syntax makes sed similar to awk and perl, which use a
  2860.    similar commenting structure in their scripts.  Thus,
  2861.  
  2862.       # GNU style sed script
  2863.       $!N;                        # except for last line, get next line
  2864.       s/^\([0-9]\{5\}\).*\n\1.*//;    # if first 5 digits of each line
  2865.                                       # match, delete BOTH lines.
  2866.       t skip
  2867.       P;                              # print 1st line only if no match
  2868.       :skip
  2869.       D;                    # delete 1st line of pattern space and loop
  2870.       #---end of script---
  2871.  
  2872.    is a valid script for GNU sed and Helman's sed, but is unrecognized
  2873.    for most other versions of sed.
  2874.  
  2875. 6.8.3. Special syntax in REs
  2876.  
  2877. A. GNU sed v2.05 and higher versions
  2878.  
  2879.    BEGIN~STEP selection: GNU sed can select a series of lines in the
  2880.    form M~N, where M and N are integers (with gsed v2.05, M must be
  2881.    less than N). Beginning at line M (M may equal 0), every Nth line
  2882.    is selected. Thus,
  2883.  
  2884.       gsed '1~3d' file    # delete every 3d line, starting with line 1
  2885.                           # deletes lines 1, 4, 7, 10, 13, 16, ...
  2886.  
  2887.       gsed -n '2~5p' file # print every 5th line, starting with line 2
  2888.                           # prints lines 2, 7, 12, 17, 22, 27, ...
  2889.  
  2890.    With gsed v3.02, M may be any valid line number. With gsed v2.05,
  2891.    if M is greater than or equal to N (the STEP value), nothing will
  2892.    be selected, except in one pointless case, 0~0, which selects every
  2893.    line.
  2894.  
  2895.    The following expressions can be used for /RE/ addresses or in the
  2896.    LHS side of a substitution:
  2897.  
  2898.       \`  - matches the beginning of the pattern space (same as "^")
  2899.       \'  - matches the end of the pattern space (same as "$")
  2900.       \?  - 0 or 1 occurrences of previous character: same as \{0,1\}
  2901.       \+  - 1 or more occurrences of previous character: same as \{1,\}
  2902.       \|  - matches the string on either side, e.g., foo\|bar
  2903.       \b  - boundary between word and nonword chars (reversible)
  2904.       \B  - boundary between 2 word or between 2 nonword chars
  2905.       \n  - embedded newline (usable after N, G, or similar commands)
  2906.       \w  - any word character: [A-Za-z0-9_]
  2907.       \W  - any nonword char: [^A-Za-z0-9_]
  2908.       \<  - boundary between nonword and word character
  2909.       \>  - boundary between word and nonword character
  2910.  
  2911.    On \b, \B, \<, and \>, see section 6.8.4 ("Word boundaries"),
  2912.    below.
  2913.  
  2914.    Beginning with version 3.02.80, the following escape sequences can
  2915.    now be used on both sides of a "s///" substitution:
  2916.  
  2917.       \a      "alert" beep     (BEL, Ctrl-G, 0x07)
  2918.       \f      formfeed         (FF, Ctrl-L, 0x0C)
  2919.       \n      newline          (LF, Ctrl-J, 0x0A)
  2920.       \r      carriage-return  (CR, Ctrl-M, 0x0D)
  2921.       \t      horizontal tab   (HT, Ctrl-I, 0x09)
  2922.       \v      vertical tab     (VT, Ctrl-K, 0x0B)
  2923.       \oNNN   a character with the octal value NNN
  2924.       \dNNN   a character with the decimal value NNN
  2925.       \xNN    a character with the hexadecimal value NN
  2926.  
  2927.    Note that gsed does not have any syntax for designating characters
  2928.    in octal or hex notation. Traditionally, \ooo or \hh or \xhh have
  2929.    been used by the GNU project to do this, but they are not (yet)
  2930.    implemented in gsed. Note that GNU sed also supports "character
  2931.    classes", a POSIX extension to regexes, described in section 3.7,
  2932.    above.
  2933.  
  2934. B. GNU sed v1.03 (by Frank Whaley)
  2935.  
  2936.    When used with the -x (extended) switch on the command line, or
  2937.    when '#x' occurs as the first line of a script, Whaley's gsed103
  2938.    supports the following expressions in both the LHS and RHS of a
  2939.    substitution:
  2940.  
  2941.       \|      matches the expression on either side
  2942.       ?       0 or 1 occurrences of previous RE: same as \{0,1\}
  2943.       +       1 or more occurrence of previous RE: same as \{1,\}
  2944.       \a      "alert" beep     (BEL, Ctrl-G, 0x07)
  2945.       \b      backspace        (BS, Ctrl-H, 0x08)
  2946.       \f      formfeed         (FF, Ctrl-L, 0x0C)
  2947.       \n      newline          (LF, Ctrl-J, 0x0A)
  2948.       \r      carriage-return  (CR, Ctrl-M, 0x0D)
  2949.       \t      horizontal tab   (HT, Ctrl-I, 0x09)
  2950.       \v      vertical tab     (VT, Ctrl-K, 0x0B)
  2951.       \bBBB   binary char, where BBB are 1-8 binary digits, [0-1]
  2952.       \dDDD   decimal char, where DDD are 1-3 decimal digits, [0-9]
  2953.       \oOOO   octal char, where OOO are 1-3 octal digits, [0-7]
  2954.       \xXX    hex char, where XX are 1-2 hex digits, [0-9A-F]
  2955.  
  2956.    In normal mode, with or without the -x switch, the following escape
  2957.    sequences are also supported in regex addressing or in the LHS of a
  2958.    substitution:
  2959.  
  2960.       \`      matches beginning of pattern space: same as /^/
  2961.       \'      matches end of pattern space: same as /$/
  2962.       \B      boundary between 2 word or 2 nonword characters
  2963.       \w      any nonword character [*BUG!* should be a word char]
  2964.       \W      any nonword character: same as /[^A-Za-z0-9]/
  2965.       \<      boundary between nonword and word char
  2966.       \>      boundary between word and nonword char
  2967.  
  2968. C. HHsed v1.5 (by Howard Helman)
  2969.  
  2970.    The following expressions can be used for /RE/ addresses or in the
  2971.    LHS and RHS side of a substitution:
  2972.  
  2973.       +    - 1 or more occurrences of previous RE: same as \{1,\}
  2974.       \a   - bell         (ASCII 07, 0x07)
  2975.       \b   - backspace    (ASCII 08, 0x08)
  2976.       \e   - escape       (ASCII 27, 0x1B)
  2977.       \f   - formfeed     (ASCII 12, 0x0C)
  2978.       \n   - newline      (printed as 2 bytes, 0D 0A or ^M^J, in DOS)
  2979.       \r   - return       (ASCII 13, 0x0D)
  2980.       \t   - tab          (ASCII 09, 0x09)
  2981.       \v   - vertical tab (ASCII 11, 0x0B)
  2982.       \xhh - the ASCII character corresponding to 2 hex digits hh.
  2983.       \<   - boundary between nonword and word character
  2984.       \>   - boundary between word and nonword character
  2985.  
  2986. D. sedmod v1.0 (by Hern Chen)
  2987.  
  2988.    The following expressions can be used for /RE/ addresses in the LHS
  2989.    of a substitution:
  2990.  
  2991.       +    - 1 or more occurrences of previous RE: same as \{1,\}
  2992.       \a   - any alphanumeric: same as [a-zA-Z0-9]
  2993.       \A   - 1 or more alphas: same as \a+
  2994.       \d   - any digit: same as [0-9]
  2995.       \D   - 1 or more digits: same as \d+
  2996.       \h   - any hex digit: same as [0-9a-fA-F]
  2997.       \H   - 1 or more hexdigits: same as \h+
  2998.       \l   - any letter: same as [A-Za-z]
  2999.       \L   - 1 or more letters: same as \l+
  3000.       \n   - newline      (read as 2 bytes, 0D 0A or ^M^J, in DOS)
  3001.       \s   - any whitespace character: space, tab, or vertical tab
  3002.       \S   - 1 or more whitespace chars: same as \s+
  3003.       \t   - tab          (ASCII 09, 0x09)
  3004.       \<   - boundary between nonword and word character
  3005.       \>   - boundary between word and nonword character
  3006.  
  3007.    The following expressions can be used in the RHS of a substitution.
  3008.    "Elements" refer to \1 .. \9, &, $0, or $1 .. $9:
  3009.  
  3010.       &    - insert regexp defined on LHS
  3011.       \e   - end case conversion of next element
  3012.       \E   - end case conversion of remaining elements
  3013.       \l   - change next element to lower case
  3014.       \L   - change remaining elements to lower case
  3015.       \n   - newline      (printed as 2 bytes, 0D 0A or ^M^J, in DOS)
  3016.       \t   - tab          (ASCII 09, 0x09)
  3017.       \u   - change next element to upper case
  3018.       \U   - change remaining elements to upper case
  3019.       $0   - insert pattern space BEFORE the substitution
  3020.       $1-$9 - match Nth word on the pattern space
  3021.  
  3022. E. UnixDos sed
  3023.  
  3024.    The following expressions can be used in text, LHS, and RHS:
  3025.  
  3026.       \n   - newline      (printed as 2 bytes, 0D 0A or ^M^J, in DOS)
  3027.  
  3028. 6.8.4. Word boundaries
  3029.  
  3030.    GNU sed, HHsed, and sedmod use certain symbols to define the
  3031.    boundary between a "word character" and a nonword character. A word
  3032.    character fits the regex "[A-Za-z0-9_]". Note: a word character
  3033.    includes the underscore "_" but not the hyphen, probably because
  3034.    the underscore is permissible as a label in sed and in other
  3035.    scripting languages. (In gsed103, a word character did NOT include
  3036.    the underscore; it included alphanumerics only.)
  3037.  
  3038.    These symbols include '\<' and '\>' (gsed, HHsed, sedmod) and '\b'
  3039.    and '\B' (gsed only). Note that the boundary symbols do not
  3040.    represent a character, but a position on the line. Word boundaries
  3041.    are used with literal characters or character sets to let you match
  3042.    (and delete or alter) whole words without affecting the spaces or
  3043.    punctuation marks outside of those words. They can only be used in
  3044.    a "/pattern/" address or in the LHS of a 's/LHS/RHS/' command. The
  3045.    following table shows how these symbols may be used in HHsed and
  3046.    GNU sed. Sedmod matches the syntax of HHsed.
  3047.  
  3048.       Match position      Possible word boundaries   HHsed   GNU sed
  3049.       ---------------------------------------------------------------
  3050.       start of word    [nonword char]^[word char]      \<    \< or \b
  3051.       end of word         [word char]^[nonword char]   \>    \> or \b
  3052.       middle of word      [word char]^[word char]     none      \B
  3053.       outside of word  [nonword char]^[nonword char]  none      \B
  3054.       ---------------------------------------------------------------
  3055.  
  3056. 6.8.5. Range addressing with GNU sed and HHsed
  3057.  
  3058.    When addressing a range of lines, as in the following example to
  3059.    delete all lines between /RE1/ and /RE2/,
  3060.  
  3061.       sed '/RE1/,/RE2/d' file
  3062.  
  3063.    if /RE1/ and /RE2/ both occur on the *same* line, HHsed will delete
  3064.    that single line and then look forward in the file for the next
  3065.    occurrence of /RE1/ to attempt the deletion. GNU sed will match the
  3066.    first line containing /RE1/ but will look forward to the next and
  3067.    succeeding lines to match /RE2/. If /RE1/ and /RE2/ cannot be found
  3068.    on two different lines, nothing will be deleted.
  3069.  
  3070.    GNU sed v2.05 has a bug in range addressing (see section 6.7.C(3),
  3071.    above). This was fixed in gsed v3.02.
  3072.  
  3073.    GNU sed v3.02.80 supports 0 in range addressing, which means that
  3074.    the range "0,/RE/" will match every line from the top of the file
  3075.    to the first line containing /RE/, inclusive, and if /RE/ occurs on
  3076.    the first line of the file, only line 1 will be matched.
  3077.  
  3078. 6.8.6. Commands which operate differently                                     |
  3079.  
  3080. A. GNU sed version 3.02 and 3.02.80                                           |
  3081.  
  3082.    The N command no longer discards the contents of the pattern space         |
  3083.    upon reaching the end of file. This is not a bug, it's a feature.          |
  3084.    However, it breaks certain scripts which relied on the older               |
  3085.    behavior of N.                                                             |
  3086.  
  3087.    'N' adds the Next line to the pattern space, enabling multiple             |
  3088.    lines to be stored and acted upon. Upon reaching the last line of          |
  3089.    the file, if the N command was issued again, the contents of the           |
  3090.    pattern space would be silently deleted and the script would abort         |
  3091.    (this has been the traditional behavior). For this reason, sed             |
  3092.    users generally wrote:                                                     |
  3093.  
  3094.       $!N;   # to add the Next line to every line but the last one.           |
  3095.    
  3096.    However, certain sed scripts relied on this behavior, such as the          |
  3097.    script to delete trailing blank lines at the end of a file (see            |
  3098.    script #12 in section 3.2, "Common one-line sed scripts", above).          |
  3099.    Also, classic textbooks such as Dale Dougherty and Arnold Robbins'         |
  3100.    _sed & awk_ documented the older behavior.                                 |
  3101.  
  3102.    The GNU sed maintainer felt that despite the portability problems          |
  3103.    this would cause, changing the N command to print (rather than             |
  3104.    delete) the pattern space was more consistent with one's intuitions        |
  3105.    about how a command to "append the Next line" _ought_ to behave.           |
  3106.    Another fact favoring the change was that "{N;command;}" will              |
  3107.    delete the last line if the file has an odd number of lines, but           |
  3108.    print the last line if the file has an even number of lines.               |
  3109.  
  3110.    To convert scripts which used the former behavior of N (deleting           |
  3111.    the pattern space upon reaching the EOF) to scripts compatible with        |
  3112.    all versions of sed, change a lone "N;" to "$d;N;".                        |
  3113.    
  3114.  
  3115. [end-of-file]
  3116.  
  3117.