Advertisement
Yunga

sed1line.txt

Jul 4th, 2015
366
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 18.91 KB | None | 0 0
  1. -------------------------------------------------------------------------
  2. USEFUL ONE-LINE SCRIPTS FOR SED (Unix stream editor)        Dec. 29, 2005
  3. Compiled by Eric Pement - pemente[at]northpark[dot]edu        version 5.5
  4.  
  5. Latest version of this file (in English) is usually at:
  6.    http://sed.sourceforge.net/sed1line.txt
  7.    http://www.pement.org/sed/sed1line.txt
  8.  
  9. This file will also available in other languages:
  10.   Chinese     - http://sed.sourceforge.net/sed1line_zh-CN.html
  11.   Czech       - http://sed.sourceforge.net/sed1line_cz.html
  12.   Dutch       - http://sed.sourceforge.net/sed1line_nl.html
  13.   French      - http://sed.sourceforge.net/sed1line_fr.html
  14.   German      - http://sed.sourceforge.net/sed1line_de.html
  15.   Italian     - http://sed.sourceforge.net/sed1line_it.html
  16.   Portuguese  - http://sed.sourceforge.net/sed1line_pt-BR.html
  17.   Spanish     - http://sed.sourceforge.net/sed1line_es.html
  18.  
  19. FILE SPACING:
  20.  
  21.  # double space a file
  22.  sed G
  23.  
  24.  # double space a file which already has blank lines in it. Output file
  25.  # should contain no more than one blank line between lines of text.
  26.  sed '/^$/d;G'
  27.  
  28.  # triple space a file
  29.  sed 'G;G'
  30.  
  31.  # undo double-spacing (assumes even-numbered lines are always blank)
  32.  sed 'n;d'
  33.  
  34.  # insert a blank line above every line which matches "regex"
  35.  sed '/regex/{x;p;x;}'
  36.  
  37.  # insert a blank line below every line which matches "regex"
  38.  sed '/regex/G'
  39.  
  40.  # insert a blank line above and below every line which matches "regex"
  41.  sed '/regex/{x;p;x;G;}'
  42.  
  43. NUMBERING:
  44.  
  45.  # number each line of a file (simple left alignment). Using a tab (see
  46.  # note on '\t' at end of file) instead of space will preserve margins.
  47.  sed = filename | sed 'N;s/\n/\t/'
  48.  
  49.  # number each line of a file (number on left, right-aligned)
  50.  sed = filename | sed 'N; s/^/     /; s/ *\(.\{6,\}\)\n/\1  /'
  51.  
  52.  # number each line of file, but only print numbers if line is not blank
  53.  sed '/./=' filename | sed '/./N; s/\n/ /'
  54.  
  55.  # count lines (emulates "wc -l")
  56.  sed -n '$='
  57.  
  58. TEXT CONVERSION AND SUBSTITUTION:
  59.  
  60.  # IN UNIX ENVIRONMENT: convert DOS newlines (CR/LF) to Unix format.
  61.  sed 's/.$//'               # assumes that all lines end with CR/LF
  62.  sed 's/^M$//'              # in bash/tcsh, press Ctrl-V then Ctrl-M
  63.  sed 's/\x0D$//'            # works on ssed, gsed 3.02.80 or higher
  64.  
  65.  # IN UNIX ENVIRONMENT: convert Unix newlines (LF) to DOS format.
  66.  sed "s/$/`echo -e \\\r`/"            # command line under ksh
  67.  sed 's/$'"/`echo \\\r`/"             # command line under bash
  68.  sed "s/$/`echo \\\r`/"               # command line under zsh
  69.  sed 's/$/\r/'                        # gsed 3.02.80 or higher
  70.  
  71.  # IN DOS ENVIRONMENT: convert Unix newlines (LF) to DOS format.
  72.  sed "s/$//"                          # method 1
  73.  sed -n p                             # method 2
  74.  
  75.  # IN DOS ENVIRONMENT: convert DOS newlines (CR/LF) to Unix format.
  76.  # Can only be done with UnxUtils sed, version 4.0.7 or higher. The
  77.  # UnxUtils version can be identified by the custom "--text" switch
  78.  # which appears when you use the "--help" switch. Otherwise, changing
  79.  # DOS newlines to Unix newlines cannot be done with sed in a DOS
  80.  # environment. Use "tr" instead.
  81.  sed "s/\r//" infile >outfile         # UnxUtils sed v4.0.7 or higher
  82.  tr -d \r <infile >outfile            # GNU tr version 1.22 or higher
  83.  
  84.  # delete leading whitespace (spaces, tabs) from front of each line
  85.  # aligns all text flush left
  86.  sed 's/^[ \t]*//'                    # see note on '\t' at end of file
  87.  
  88.  # delete trailing whitespace (spaces, tabs) from end of each line
  89.  sed 's/[ \t]*$//'                    # see note on '\t' at end of file
  90.  
  91.  # delete BOTH leading and trailing whitespace from each line
  92.  sed 's/^[ \t]*//;s/[ \t]*$//'
  93.  
  94.  # insert 5 blank spaces at beginning of each line (make page offset)
  95.  sed 's/^/     /'
  96.  
  97.  # align all text flush right on a 79-column width
  98.  sed -e :a -e 's/^.\{1,78\}$/ &/;ta'  # set at 78 plus 1 space
  99.  
  100.  # center all text in the middle of 79-column width. In method 1,
  101.  # spaces at the beginning of the line are significant, and trailing
  102.  # spaces are appended at the end of the line. In method 2, spaces at
  103.  # the beginning of the line are discarded in centering the line, and
  104.  # no trailing spaces appear at the end of lines.
  105.  sed  -e :a -e 's/^.\{1,77\}$/ & /;ta'                     # method 1
  106.  sed  -e :a -e 's/^.\{1,77\}$/ &/;ta' -e 's/\( *\)\1/\1/'  # method 2
  107.  
  108.  # substitute (find and replace) "foo" with "bar" on each line
  109.  sed 's/foo/bar/'             # replaces only 1st instance in a line
  110.  sed 's/foo/bar/4'            # replaces only 4th instance in a line
  111.  sed 's/foo/bar/g'            # replaces ALL instances in a line
  112.  sed 's/\(.*\)foo\(.*foo\)/\1bar\2/' # replace the next-to-last case
  113.  sed 's/\(.*\)foo/\1bar/'            # replace only the last case
  114.  
  115.  # substitute "foo" with "bar" ONLY for lines which contain "baz"
  116.  sed '/baz/s/foo/bar/g'
  117.  
  118.  # substitute "foo" with "bar" EXCEPT for lines which contain "baz"
  119.  sed '/baz/!s/foo/bar/g'
  120.  
  121.  # change "scarlet" or "ruby" or "puce" to "red"
  122.  sed 's/scarlet/red/g;s/ruby/red/g;s/puce/red/g'   # most seds
  123.  gsed 's/scarlet\|ruby\|puce/red/g'                # GNU sed only
  124.  
  125.  # reverse order of lines (emulates "tac")
  126.  # bug/feature in HHsed v1.5 causes blank lines to be deleted
  127.  sed '1!G;h;$!d'               # method 1
  128.  sed -n '1!G;h;$p'             # method 2
  129.  
  130.  # reverse each character on the line (emulates "rev")
  131.  sed '/\n/!G;s/\(.\)\(.*\n\)/&\2\1/;//D;s/.//'
  132.  
  133.  # join pairs of lines side-by-side (like "paste")
  134.  sed '$!N;s/\n/ /'
  135.  
  136.  # if a line ends with a backslash, append the next line to it
  137.  sed -e :a -e '/\\$/N; s/\\\n//; ta'
  138.  
  139.  # if a line begins with an equal sign, append it to the previous line
  140.  # and replace the "=" with a single space
  141.  sed -e :a -e '$!N;s/\n=/ /;ta' -e 'P;D'
  142.  
  143.  # add commas to numeric strings, changing "1234567" to "1,234,567"
  144.  gsed ':a;s/\B[0-9]\{3\}\>/,&/;ta'                     # GNU sed
  145.  sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta'  # other seds
  146.  
  147.  # add commas to numbers with decimal points and minus signs (GNU sed)
  148.  gsed -r ':a;s/(^|[^0-9.])([0-9]+)([0-9]{3})/\1\2,\3/g;ta'
  149.  
  150.  # add a blank line every 5 lines (after lines 5, 10, 15, 20, etc.)
  151.  gsed '0~5G'                  # GNU sed only
  152.  sed 'n;n;n;n;G;'             # other seds
  153.  
  154. SELECTIVE PRINTING OF CERTAIN LINES:
  155.  
  156.  # print first 10 lines of file (emulates behavior of "head")
  157.  sed 10q
  158.  
  159.  # print first line of file (emulates "head -1")
  160.  sed q
  161.  
  162.  # print the last 10 lines of a file (emulates "tail")
  163.  sed -e :a -e '$q;N;11,$D;ba'
  164.  
  165.  # print the last 2 lines of a file (emulates "tail -2")
  166.  sed '$!N;$!D'
  167.  
  168.  # print the last line of a file (emulates "tail -1")
  169.  sed '$!d'                    # method 1
  170.  sed -n '$p'                  # method 2
  171.  
  172.  # print the next-to-the-last line of a file
  173.  sed -e '$!{h;d;}' -e x              # for 1-line files, print blank line
  174.  sed -e '1{$q;}' -e '$!{h;d;}' -e x  # for 1-line files, print the line
  175.  sed -e '1{$d;}' -e '$!{h;d;}' -e x  # for 1-line files, print nothing
  176.  
  177.  # print only lines which match regular expression (emulates "grep")
  178.  sed -n '/regexp/p'           # method 1
  179.  sed '/regexp/!d'             # method 2
  180.  
  181.  # print only lines which do NOT match regexp (emulates "grep -v")
  182.  sed -n '/regexp/!p'          # method 1, corresponds to above
  183.  sed '/regexp/d'              # method 2, simpler syntax
  184.  
  185.  # print the line immediately before a regexp, but not the line
  186.  # containing the regexp
  187.  sed -n '/regexp/{g;1!p;};h'
  188.  
  189.  # print the line immediately after a regexp, but not the line
  190.  # containing the regexp
  191.  sed -n '/regexp/{n;p;}'
  192.  
  193.  # print 1 line of context before and after regexp, with line number
  194.  # indicating where the regexp occurred (similar to "grep -A1 -B1")
  195.  sed -n -e '/regexp/{=;x;1!p;g;$!N;p;D;}' -e h
  196.  
  197.  # grep for AAA and BBB and CCC (in any order)
  198.  sed '/AAA/!d; /BBB/!d; /CCC/!d'
  199.  
  200.  # grep for AAA and BBB and CCC (in that order)
  201.  sed '/AAA.*BBB.*CCC/!d'
  202.  
  203.  # grep for AAA or BBB or CCC (emulates "egrep")
  204.  sed -e '/AAA/b' -e '/BBB/b' -e '/CCC/b' -e d    # most seds
  205.  gsed '/AAA\|BBB\|CCC/!d'                        # GNU sed only
  206.  
  207.  # print paragraph if it contains AAA (blank lines separate paragraphs)
  208.  # HHsed v1.5 must insert a 'G;' after 'x;' in the next 3 scripts below
  209.  sed -e '/./{H;$!d;}' -e 'x;/AAA/!d;'
  210.  
  211.  # print paragraph if it contains AAA and BBB and CCC (in any order)
  212.  sed -e '/./{H;$!d;}' -e 'x;/AAA/!d;/BBB/!d;/CCC/!d'
  213.  
  214.  # print paragraph if it contains AAA or BBB or CCC
  215.  sed -e '/./{H;$!d;}' -e 'x;/AAA/b' -e '/BBB/b' -e '/CCC/b' -e d
  216.  gsed '/./{H;$!d;};x;/AAA\|BBB\|CCC/b;d'         # GNU sed only
  217.  
  218.  # print only lines of 65 characters or longer
  219.  sed -n '/^.\{65\}/p'
  220.  
  221.  # print only lines of less than 65 characters
  222.  sed -n '/^.\{65\}/!p'        # method 1, corresponds to above
  223.  sed '/^.\{65\}/d'            # method 2, simpler syntax
  224.  
  225.  # print section of file from regular expression to end of file
  226.  sed -n '/regexp/,$p'
  227.  
  228.  # print section of file based on line numbers (lines 8-12, inclusive)
  229.  sed -n '8,12p'               # method 1
  230.  sed '8,12!d'                 # method 2
  231.  
  232.  # print line number 52
  233.  sed -n '52p'                 # method 1
  234.  sed '52!d'                   # method 2
  235.  sed '52q;d'                  # method 3, efficient on large files
  236.  
  237.  # beginning at line 3, print every 7th line
  238.  gsed -n '3~7p'               # GNU sed only
  239.  sed -n '3,${p;n;n;n;n;n;n;}' # other seds
  240.  
  241.  # print section of file between two regular expressions (inclusive)
  242.  sed -n '/Iowa/,/Montana/p'             # case sensitive
  243.  
  244. SELECTIVE DELETION OF CERTAIN LINES:
  245.  
  246.  # print all of file EXCEPT section between 2 regular expressions
  247.  sed '/Iowa/,/Montana/d'
  248.  
  249.  # delete duplicate, consecutive lines from a file (emulates "uniq").
  250.  # First line in a set of duplicate lines is kept, rest are deleted.
  251.  sed '$!N; /^\(.*\)\n\1$/!P; D'
  252.  
  253.  # delete duplicate, nonconsecutive lines from a file. Beware not to
  254.  # overflow the buffer size of the hold space, or else use GNU sed.
  255.  sed -n 'G; s/\n/&&/; /^\([ -~]*\n\).*\n\1/d; s/\n//; h; P'
  256.  
  257.  # delete all lines except duplicate lines (emulates "uniq -d").
  258.  sed '$!N; s/^\(.*\)\n\1$/\1/; t; D'
  259.  
  260.  # delete the first 10 lines of a file
  261.  sed '1,10d'
  262.  
  263.  # delete the last line of a file
  264.  sed '$d'
  265.  
  266.  # delete the last 2 lines of a file
  267.  sed 'N;$!P;$!D;$d'
  268.  
  269.  # delete the last 10 lines of a file
  270.  sed -e :a -e '$d;N;2,10ba' -e 'P;D'   # method 1
  271.  sed -n -e :a -e '1,10!{P;N;D;};N;ba'  # method 2
  272.  
  273.  # delete every 8th line
  274.  gsed '0~8d'                           # GNU sed only
  275.  sed 'n;n;n;n;n;n;n;d;'                # other seds
  276.  
  277.  # delete lines matching pattern
  278.  sed '/pattern/d'
  279.  
  280.  # delete ALL blank lines from a file (same as "grep '.' ")
  281.  sed '/^$/d'                           # method 1
  282.  sed '/./!d'                           # method 2
  283.  
  284.  # delete all CONSECUTIVE blank lines from file except the first; also
  285.  # deletes all blank lines from top and end of file (emulates "cat -s")
  286.  sed '/./,/^$/!d'          # method 1, allows 0 blanks at top, 1 at EOF
  287.  sed '/^$/N;/\n$/D'        # method 2, allows 1 blank at top, 0 at EOF
  288.  
  289.  # delete all CONSECUTIVE blank lines from file except the first 2:
  290.  sed '/^$/N;/\n$/N;//D'
  291.  
  292.  # delete all leading blank lines at top of file
  293.  sed '/./,$!d'
  294.  
  295.  # delete all trailing blank lines at end of file
  296.  sed -e :a -e '/^\n*$/{$d;N;ba' -e '}'  # works on all seds
  297.  sed -e :a -e '/^\n*$/N;/\n$/ba'        # ditto, except for gsed 3.02.*
  298.  
  299.  # delete the last line of each paragraph
  300.  sed -n '/^$/{p;h;};/./{x;/./p;}'
  301.  
  302. SPECIAL APPLICATIONS:
  303.  
  304.  # remove nroff overstrikes (char, backspace) from man pages. The 'echo'
  305.  # command may need an -e switch if you use Unix System V or bash shell.
  306.  sed "s/.`echo \\\b`//g"    # double quotes required for Unix environment
  307.  sed 's/.^H//g'             # in bash/tcsh, press Ctrl-V and then Ctrl-H
  308.  sed 's/.\x08//g'           # hex expression for sed 1.5, GNU sed, ssed
  309.  
  310.  # get Usenet/e-mail message header
  311.  sed '/^$/q'                # deletes everything after first blank line
  312.  
  313.  # get Usenet/e-mail message body
  314.  sed '1,/^$/d'              # deletes everything up to first blank line
  315.  
  316.  # get Subject header, but remove initial "Subject: " portion
  317.  sed '/^Subject: */!d; s///;q'
  318.  
  319.  # get return address header
  320.  sed '/^Reply-To:/q; /^From:/h; /./d;g;q'
  321.  
  322.  # parse out the address proper. Pulls out the e-mail address by itself
  323.  # from the 1-line return address header (see preceding script)
  324.  sed 's/ *(.*)//; s/>.*//; s/.*[:<] *//'
  325.  
  326.  # add a leading angle bracket and space to each line (quote a message)
  327.  sed 's/^/> /'
  328.  
  329.  # delete leading angle bracket & space from each line (unquote a message)
  330.  sed 's/^> //'
  331.  
  332.  # remove most HTML tags (accommodates multiple-line tags)
  333.  sed -e :a -e 's/<[^>]*>//g;/</N;//ba'
  334.  
  335.  # extract multi-part uuencoded binaries, removing extraneous header
  336.  # info, so that only the uuencoded portion remains. Files passed to
  337.  # sed must be passed in the proper order. Version 1 can be entered
  338.  # from the command line; version 2 can be made into an executable
  339.  # Unix shell script. (Modified from a script by Rahul Dhesi.)
  340.  sed '/^end/,/^begin/d' file1 file2 ... fileX | uudecode   # vers. 1
  341.  sed '/^end/,/^begin/d' "$@" | uudecode                    # vers. 2
  342.  
  343.  # sort paragraphs of file alphabetically. Paragraphs are separated by blank
  344.  # lines. GNU sed uses \v for vertical tab, or any unique char will do.
  345.  sed '/./{H;d;};x;s/\n/={NL}=/g' file | sort | sed '1s/={NL}=//;s/={NL}=/\n/g'
  346.  gsed '/./{H;d};x;y/\n/\v/' file | sort | sed '1s/\v//;y/\v/\n/'
  347.  
  348.  # zip up each .TXT file individually, deleting the source file and
  349.  # setting the name of each .ZIP file to the basename of the .TXT file
  350.  # (under DOS: the "dir /b" switch returns bare filenames in all caps).
  351.  echo @echo off >zipup.bat
  352.  dir /b *.txt | sed "s/^\(.*\)\.TXT/pkzip -mo \1 \1.TXT/" >>zipup.bat
  353.  
  354. TYPICAL USE: Sed takes one or more editing commands and applies all of
  355. them, in sequence, to each line of input. After all the commands have
  356. been applied to the first input line, that line is output and a second
  357. input line is taken for processing, and the cycle repeats. The
  358. preceding examples assume that input comes from the standard input
  359. device (i.e, the console, normally this will be piped input). One or
  360. more filenames can be appended to the command line if the input does
  361. not come from stdin. Output is sent to stdout (the screen). Thus:
  362.  
  363.  cat filename | sed '10q'        # uses piped input
  364.  sed '10q' filename              # same effect, avoids a useless "cat"
  365.  sed '10q' filename > newfile    # redirects output to disk
  366.  
  367. For additional syntax instructions, including the way to apply editing
  368. commands from a disk file instead of the command line, consult "sed &
  369. awk, 2nd Edition," by Dale Dougherty and Arnold Robbins (O'Reilly,
  370. 1997; http://www.ora.com), "UNIX Text Processing," by Dale Dougherty
  371. and Tim O'Reilly (Hayden Books, 1987) or the tutorials by Mike Arst
  372. distributed in U-SEDIT2.ZIP (many sites). To fully exploit the power
  373. of sed, one must understand "regular expressions." For this, see
  374. "Mastering Regular Expressions" by Jeffrey Friedl (O'Reilly, 1997).
  375. The manual ("man") pages on Unix systems may be helpful (try "man
  376. sed", "man regexp", or the subsection on regular expressions in "man
  377. ed"), but man pages are notoriously difficult. They are not written to
  378. teach sed use or regexps to first-time users, but as a reference text
  379. for those already acquainted with these tools.
  380.  
  381. QUOTING SYNTAX: The preceding examples use single quotes ('...')
  382. instead of double quotes ("...") to enclose editing commands, since
  383. sed is typically used on a Unix platform. Single quotes prevent the
  384. Unix shell from intrepreting the dollar sign ($) and backquotes
  385. (`...`), which are expanded by the shell if they are enclosed in
  386. double quotes. Users of the "csh" shell and derivatives will also need
  387. to quote the exclamation mark (!) with the backslash (i.e., \!) to
  388. properly run the examples listed above, even within single quotes.
  389. Versions of sed written for DOS invariably require double quotes
  390. ("...") instead of single quotes to enclose editing commands.
  391.  
  392. USE OF '\t' IN SED SCRIPTS: For clarity in documentation, we have used
  393. the expression '\t' to indicate a tab character (0x09) in the scripts.
  394. However, most versions of sed do not recognize the '\t' abbreviation,
  395. so when typing these scripts from the command line, you should press
  396. the TAB key instead. '\t' is supported as a regular expression
  397. metacharacter in awk, perl, and HHsed, sedmod, and GNU sed v3.02.80.
  398.  
  399. VERSIONS OF SED: Versions of sed do differ, and some slight syntax
  400. variation is to be expected. In particular, most do not support the
  401. use of labels (:name) or branch instructions (b,t) within editing
  402. commands, except at the end of those commands. We have used the syntax
  403. which will be portable to most users of sed, even though the popular
  404. GNU versions of sed allow a more succinct syntax. When the reader sees
  405. a fairly long command such as this:
  406.  
  407.   sed -e '/AAA/b' -e '/BBB/b' -e '/CCC/b' -e d
  408.  
  409. it is heartening to know that GNU sed will let you reduce it to:
  410.  
  411.   sed '/AAA/b;/BBB/b;/CCC/b;d'      # or even
  412.   sed '/AAA\|BBB\|CCC/b;d'
  413.  
  414. In addition, remember that while many versions of sed accept a command
  415. like "/one/ s/RE1/RE2/", some do NOT allow "/one/! s/RE1/RE2/", which
  416. contains space before the 's'. Omit the space when typing the command.
  417.  
  418. OPTIMIZING FOR SPEED: If execution speed needs to be increased (due to
  419. large input files or slow processors or hard disks), substitution will
  420. be executed more quickly if the "find" expression is specified before
  421. giving the "s/.../.../" instruction. Thus:
  422.  
  423.   sed 's/foo/bar/g' filename         # standard replace command
  424.   sed '/foo/ s/foo/bar/g' filename   # executes more quickly
  425.   sed '/foo/ s//bar/g' filename      # shorthand sed syntax
  426.  
  427. On line selection or deletion in which you only need to output lines
  428. from the first part of the file, a "quit" command (q) in the script
  429. will drastically reduce processing time for large files. Thus:
  430.  
  431.   sed -n '45,50p' filename           # print line nos. 45-50 of a file
  432.   sed -n '51q;45,50p' filename       # same, but executes much faster
  433.  
  434. If you have any additional scripts to contribute or if you find errors
  435. in this document, please send e-mail to the compiler. Indicate the
  436. version of sed you used, the operating system it was compiled for, and
  437. the nature of the problem. To qualify as a one-liner, the command line
  438. must be 65 characters or less. Various scripts in this file have been
  439. written or contributed by:
  440.  
  441. Al Aab                   # founder of "seders" list
  442. Edgar Allen              # various
  443. Yiorgos Adamopoulos      # various
  444. Dale Dougherty           # author of "sed & awk"
  445. Carlos Duarte            # author of "do it with sed"
  446. Eric Pement              # author of this document
  447. Ken Pizzini              # author of GNU sed v3.02
  448. S.G. Ravenhall           # great de-html script
  449. Greg Ubben               # many contributions & much help
  450. -------------------------------------------------------------------------
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement