sed1line.txt 17 KB

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