Table of Contents
- 1. sed (Stream EDitor)
- 2. Synopsis
- 3. Synopsis
- 4. Command syntax
- 5. Commands
- 6. Examples
- 7. Quines
- 8. Exercises
- 9. Links
- 10. Books
- 10.1. "sed & awk, 2nd Edition," by Dale Dougherty and Arnold Robbins (O'Reilly, 1997)
- 10.2. "UNIX Text Processing," by Dale Dougherty and Tim O'Reilly (Hayden Books, 1987)
- 10.3. Tutorials by Mike Arst distributed in U-sedIT2.ZIP (many sites)
- 10.4. "Mastering Regular Expressions" by Jeffrey Friedl (O'Reilly, 1997)
- 10.5. The manual ("man") pages on Unix systems may be helpful (try "man sed", "man regexp", or the subsection on regular expressions in "man ed")
1. sed (Stream EDitor)
Non interactive editor, also called an stream editor Sed is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline). While in some ways similar to an editor which permits scripted edits (such as ed), sed works by making only one pass over the input(s), and is consequently more efficient. But it is sed's ability to filter text in a pipeline which particularly distinguishes it from other types of editors. By default is LINE ORIENTED. TODO: Here docs <<
2. Synopsis
sed [options] [file ... ]
2.1. Options
-n no print -e script -f script file -i edit files in place -z separate lines by NUL characters
3. Synopsis
sed [options] [file ... ]
3.1. Options
-n no print -e script -f script file -i edit files in place -z separate lines by NUL characters
4. Command syntax
[ADDRESSES][!]COMMAND Executes COMMAND using ADDRESSES. If ! is present COMMAND is executed only if ADDRESSES don't match
5. Commands
5.1. ; Separator
5.2. Addresses
0 Command is executed for all input lines
1 Command is executed for input lines that match the address
2 Command is executed for input lines that match:
<addr1>,<addr2> lines between start and end addresses:
0,<addr2> lines from begining to <addr2>
<addr1>,$ lines from <addr1> to end of input
<addr1>,+<number> <addr1> and the following <number> lines
<addr1>,~<number> <addr1> and the lines following <addr1> until line number is a multiple of <number>
Addres types <addrN>
<number> Match line with number <number>
<first>~<step> Match every <step>'th starting with <first>
$ Match last line
/<regexp>/ Match lines matching <regexp>
IS Input Stream
OS Output Stream
PS Pattern space
HB Hold buffer
Modifies
Command Addr IS OS PS HB Description
:label 0 - - - - Label for b and t commands
# 0 - - - - Comment
= 0 - Y - - Current line number
} 0 - - - - Close command block
{ 2 - - - - Begin command block
a 1 - Y - - Append <text>
b 2 - - - - Branch to label
c 2 - Y - - Replace with <text>
d 2 Y - Y - Delete PS
D 2 Y - Y - Delete first line of PS
g 2 - - Y - Copy HB to PS
G 2 - - Y - Append HB to PS
h 2 - - - Y Copy PS to HB
H 2 - - - Y Append PS to HB
i 1 - Y - - Insert
l 1 - Y - - List current line breaking <widht> characters
n 2 Y * - - Read next line of input into PS
N 2 Y - Y - Append next line of input to PS
p 2 - Y - - Print current PS
P 2 - Y - - Print first line of PS
q 1 - - - - Quit with <exitcode>
Q 1 - - - - Quit with <exitcode> not proccessing any more input
r 1 - Y - - Append text read from <filename>
s 2 - - - Y Substitute /<regexp>/<replacement>/
t 2 - - - - Test last s command and branch to label if success
T 2 - - - - Test last s command and branch to label if not success
w 2 - Y - - Write PS to <filename>
W 2 - Y - - Write first line of PS to <filename>
x 2 - - Y Y Exchange contents of PS and HB
y 2 - - Y - Transform /<source>/<destination>/
b t and T : if no label given, branch to end of script
<regexp>
^ matches empty string at the begining of line
$ matches empty string at the end of line
[<chars>]
[^<chars>]
[<char>-<char>]
[[:alnum:]]
[[:alpha:]]
[[:cntrl:]]
[[:digit:]]
[[:graph:]]
[[:lower:]]
[[:print:]]
[[:punct:]]
[[:space:]]
[[:upper:]]
[[:xdigit:]]
\w equals to [[:alnum:]]
\W equals to [^[:alnum:]]
\< matches empty string at the begining of word
\> matches empty string at end of word
\b matches empty string at the begining or end of word
\B matches empty string not at the begining or end of word
.
\?
*
\+
\|
\{n\}
\{n,\}
\{,m\}
\{n,m\}
\(\)
Precedence: iteration concatenation alternation <replacement> \[1-9] Replace partial match & Replace matched string <source> <destination> List of chars
6. Examples
6.1. File spacing
# double space a file
sed G
# triple space a file
sed 'G;G'
# delete empty lines
sed '/^$/d'
# insert a blank line above every line which matches "regex"
sed '/regex/{x;p;x}'
# insert a blank line below every line which matches "regex"
sed '/regex/G'
6.2. Numbering
# number each line of a file, using tabs
sed = filename | sed 'N;s/\n/\t/'
#+BEGIN_SRC
# number each line of a file (number on left, right-aligned)
sed = filename | sed 'N; s/^/ /; s/ *\(.\{6,\}\)\n/\1 /'
# number each line of file, but only print numbers if line is not blank
sed '/./=' filename | sed '/./N; s/\n/ /'
# count lines (emulates "wc -l")
sed -n '$='
6.3. Text conversion and substitution
# IN UNIX ENVIRONMENT: convert DOS newlines (CR/LF) to Unix format.
sed 's/.$//' # assumes that all lines end with CR/LF
sed 's/^M$//' # in bash/tcsh, press Ctrl-V then Ctrl-M
sed 's/\x0D$//' # works on ssed, gsed 3.02.80 or higher
# IN UNIX ENVIRONMENT: convert Unix newlines (LF) to DOS format.
sed "s/$/`echo -e \\\r`/" # command line under ksh
sed 's/$'"/`echo \\\r`/" # command line under bash
sed "s/$/`echo \\\r`/" # command line under zsh
sed 's/$/\r/' # gsed 3.02.80 or higher
# IN DOS ENVIRONMENT: convert Unix newlines (LF) to DOS format.
sed "s/$//" # method 1
sed -n p # method 2
# IN DOS ENVIRONMENT: convert DOS newlines (CR/LF) to Unix format. Can only be done with UnxUtils sed, version 4.0.7 or higher. The UnxUtils version can be identified by the custom "--text" switch which appears when you use the "--help" switch. Otherwise, changing DOS newlines to Unix newlines cannot be done with sed in a DOS environment. Use "tr" instead.
sed "s/\r//" infile >outfile # UnxUtils sed v4.0.7 or higher
tr -d \r <infile >outfile # GNU tr version 1.22 or higher
# delete leading whitespace (spaces, tabs) from front of each line aligns all text flush left
sed 's/^[ \t]*//' # see note on '\t' at end of file
# delete trailing whitespace (spaces, tabs) from end of each line
sed 's/[ \t]*$//' # see note on '\t' at end of file
# delete BOTH leading and trailing whitespace from each line
sed 's/^[ \t]*//;s/[ \t]*$//'
# insert 5 blank spaces at beginning of each line (make page offset)
sed 's/^/ /'
# align all text flush right on a 79-column width
sed -e :a -e 's/^.\{1,78\}$/ &/;ta' # set at 78 plus 1 space center all text in the middle of 79-column width. In method 1, spaces at the beginning of the line are significant, and trailing spaces are appended at the end of the line. In method 2, spaces at the beginning of the line are discarded in centering the line, and no trailing spaces appear at the end of lines.
sed -e :a -e 's/^.\{1,77\}$/ & /;ta' # method 1
sed -e :a -e 's/^.\{1,77\}$/ &/;ta' -e 's/\( *\)\1/\1/' # method 2 substitute (find and replace) "foo" with "bar" on each line
sed 's/foo/bar/' # replaces only 1st instance in a line
sed 's/foo/bar/4' # replaces only 4th instance in a line
sed 's/foo/bar/g' # replaces ALL instances in a line
sed 's/\(.*\)foo\(.*foo\)/\1bar\2/' # replace the next-to-last case
sed 's/\(.*\)foo/\1bar/' # replace only the last case substitute "foo" with "bar" ONLY for lines which contain "baz"
sed '/baz/s/foo/bar/g'
# substitute "foo" with "bar" EXCEPT for lines which contain "baz"
sed '/baz/!s/foo/bar/g'
# change "scarlet" or "ruby" or "puce" to "red"
sed 's/scarlet/red/g;s/ruby/red/g;s/puce/red/g' # most seds
gsed 's/scarlet\|ruby\|puce/red/g' # GNU sed only reverse order of lines (emulates "tac") bug/feature in HHsed v1.5 causes blank lines to be deleted
sed '1!G;h;$!d' # method 1
sed -n '1!G;h;$p' # method 2
# reverse each character on the line (emulates "rev")
sed '/\n/!G;s/\(.\)\(.*\n\)/&\2\1/;//D;s/.//'
# join pairs of lines side-by-side (like "paste")
sed '$!N;s/\n/ /'
# if a line ends with a backslash, append the next line to it
sed -e :a -e '/\\$/N; s/\\\n//; ta'
# if a line begins with an equal sign, append it to the previous line and replace the "=" with a single space
sed -e :a -e '$!N;s/\n=/ /;ta' -e 'P;D'
# add commas to numeric strings, changing "1234567" to "1,234,567"
gsed ':a;s/\B[0-9]\{3\}\>/,&/;ta' # GNU sed
sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta' # other seds add commas to numbers with decimal points and minus signs (GNU sed)
gsed -r ':a;s/(^|[^0-9.])([0-9]+)([0-9]{3})/\1\2,\3/g;ta'
# add a blank line every 5 lines (after lines 5, 10, 15, 20, etc.)
gsed '0~5G' # GNU sed only
sed 'n;n;n;n;G;' # other seds
6.4. Selective printing of certain lines:
# Print first 10 lines of file (emulates behavior of "head")
sed 10Q
# Print first line of file (emulates "head -1")
sed Q
# Print the last 10 lines of a file (emulates "tail")
sed -E :A -E '$Q;n;11,$d;BA'
# Print the last 2 lines of a file (emulates "tail -2")
sed '$!n;$!d'
# Print the last line of a file (emulates "tail -1")
sed '$!D' # Method 1
sed -N '$P' # Method 2
# Print the next-to-the-last line of a file
sed -E '$!{H;D;}' -E X # For 1-line files, print blank line
sed -E '1{$Q;}' -E '$!{H;D;}' -E X # For 1-line files, print the line
sed -E '1{$D;}' -E '$!{H;D;}' -E X # For 1-line files, print nothing
# Print only lines which match regular expression (emulates "grep")
sed -N '/REGEXP/P' # Method 1
sed '/REGEXP/!D' # Method 2
# PRINT ONLY LINES WHICH DO not MATCH REGEXP (EMULATES "GREP -V")
sed -N '/REGEXP/!P' # Method 1, CORRESPONDS TO ABOVE
sed '/REGEXP/D' # Method 2, SIMPLER SYNTAX
# PRINT THE LINE IMMEDIATELY BEFORE A REGEXP, BUT NOT THE LINE
# CONTAINING THE REGEXP
sed -N '/REGEXP/{G;1!P;};H'
# PRINT THE LINE IMMEDIATELY AFTER A REGEXP, BUT NOT THE LINE
# CONTAINING THE REGEXP
sed -N '/REGEXP/{N;P;}'
# PRINT 1 LINE OF CONTEXT BEFORE AND AFTER REGEXP, WITH LINE NUMBER
# INDICATING WHERE THE REGEXP OCCURRED (SIMILAR TO "GREP -a1 -b1")
sed -N -E '/REGEXP/{=;X;1!P;G;$!n;P;d;}' -E H
# GREP FOR aaa AND bbb AND ccc (IN ANY ORDER)
sed '/aaa/!D; /bbb/!D; /ccc/!D'
# GREP FOR aaa AND bbb AND ccc (IN THAT ORDER)
sed '/aaa.*bbb.*ccc/!D'
# GREP FOR aaa OR bbb OR ccc (EMULATES "EGREP")
sed -E '/aaa/B' -E '/bbb/B' -E '/ccc/B' -E D # MOST sedS
Gsed '/aaa\|bbb\|ccc/!D' # gnu sed ONLY
# PRINT PARAGRAPH IF IT CONTAINS aaa (BLANK LINES SEPARATE PARAGRAPHS)
# sed V1.5 MUST INSERT A 'g;' AFTER 'X;' IN THE NEXT 3 SCRIPTS BELOW
sed -E '/./{h;$!D;}' -E 'X;/aaa/!D;'
# PRINT PARAGRAPH IF IT CONTAINS aaa AND bbb AND ccc (IN ANY ORDER)
sed -E '/./{h;$!D;}' -E 'X;/aaa/!D;/bbb/!D;/ccc/!D'
# PRINT PARAGRAPH IF IT CONTAINS aaa OR bbb OR ccc
sed -E '/./{h;$!D;}' -E 'X;/aaa/B' -E '/bbb/B' -E '/ccc/B' -E D
Gsed '/./{h;$!D;};X;/aaa\|bbb\|ccc/B;D' # gnu sed ONLY
# PRINT ONLY LINES OF 65 CHARACTERS OR LONGER
sed -N '/^.\{65\}/P'
# PRINT ONLY LINES OF LESS THAN 65 CHARACTERS
sed -N '/^.\{65\}/!P' # Method 1, CORRESPONDS TO ABOVE
sed '/^.\{65\}/D' # Method 2, SIMPLER SYNTAX
# PRINT SECTION OF FILE FROM REGULAR EXPRESSION TO END OF FILE
sed -N '/REGEXP/,$P'
# PRINT SECTION OF FILE BAsed ON LINE NUMBERS (LINES 8-12, INCLUSIVE)
sed -N '8,12P' # Method 1
sed '8,12!D' # Method 2
# PRINT LINE NUMBER 52
sed -N '52P' # Method 1
sed '52!D' # Method 2
sed '52Q;D' # Method 3, efficient on large files
# BEGINNING AT LINE 3, PRINT EVERY 7TH LINE
Gsed -N '3~7P' # gnu sed ONLY
sed -N '3,${P;N;N;N;N;N;N;}' # OTHER sedS
# PRINT SECTION OF FILE BETWEEN TWO REGULAR EXPRESSIONS (INCLUSIVE)
sed -N '/iOWA/,/mONTANA/P' # CASE SENSITIVE
6.5. Selective deletion of certain lines:
# print all of file EXCEPT section between 2 regular expressions
sed '/Iowa/,/Montana/d'
# delete duplicate, consecutive lines from a file (emulates "uniq").
# First line in a set of duplicate lines is kept, rest are deleted.
sed '$!N; /^\(.*\)\n\1$/!P; D'
# delete duplicate, nonconsecutive lines from a file. Beware not to
# overflow the buffer size of the hold space, or else use GNU sed.
sed -n 'G; s/\n/&&/; /^\([ -~]*\n\).*\n\1/d; s/\n//; h; P'
# delete all lines except duplicate lines (emulates "uniq -d").
sed '$!N; s/^\(.*\)\n\1$/\1/; t; D'
# delete the first 10 lines of a file
sed '1,10d'
# delete the last line of a file
sed '$d'
# delete the last 2 lines of a file
sed 'N;$!P;$!D;$d'
# delete the last 10 lines of a file
sed -e :a -e '$d;N;2,10ba' -e 'P;D' # method 1
sed -n -e :a -e '1,10!{P;N;D;};N;ba' # method 2
# delete every 8th line
gsed '0~8d' # GNU sed only
sed 'n;n;n;n;n;n;n;d;' # other seds
# delete lines matching pattern
sed '/pattern/d'
# delete ALL blank lines from a file (same as "grep '.' ")
sed '/^$/d' # method 1
sed '/./!d' # method 2
# delete all CONSECUTIVE blank lines from file except the first; also
# deletes all blank lines from top and end of file (emulates "cat -s")
sed '/./,/^$/!d' # method 1, allows 0 blanks at top, 1 at EOF
sed '/^$/N;/\n$/D' # method 2, allows 1 blank at top, 0 at EOF
# delete all CONSECUTIVE blank lines from file except the first 2:
sed '/^$/N;/\n$/N;//D'
# delete all leading blank lines at top of file
sed '/./,$!d'
# delete all trailing blank lines at end of file
sed -e :a -e '/^\n*$/{$d;N;ba' -e '}' # works on all seds
sed -e :a -e '/^\n*$/N;/\n$/ba' # ditto, except for gsed 3.02.*
# delete the last line of each paragraph
sed -n '/^$/{p;h;};/./{x;/./p;}'
6.6. Special applications:
# remove nroff overstrikes (char, backspace) from man pages. The 'echo'
# command may need an -e switch if you use Unix System V or bash shell.
sed "s/.`echo \\\b`//g" # double quotes required for Unix environment
sed 's/.^H//g' # in bash/tcsh, press Ctrl-V and then Ctrl-H
sed 's/.\x08//g' # hex expression for sed 1.5, GNU sed, ssed
# get Usenet/e-mail message header
sed '/^$/q' # deletes everything after first blank line
# get Usenet/e-mail message body
sed '1,/^$/d' # deletes everything up to first blank line
# get Subject header, but remove initial "Subject: " portion
sed '/^Subject: */!d; s///;q'
# get return address header
sed '/^Reply-To:/q; /^From:/h; /./d;g;q'
# parse out the address proper. Pulls out the e-mail address by itself
# from the 1-line return address header (see preceding script)
sed 's/ *(.*)//; s/>.*//; s/.*[:<] *//'
# add a leading angle bracket and space to each line (quote a message)
sed 's/^/> /'
# delete leading angle bracket & space from each line (unquote a message)
sed 's/^> //'
# remove most HTML tags (accommodates multiple-line tags)
sed -e :a -e 's/<[^>]*>//g;/</N;//ba'
# extract multi-part uuencoded binaries, removing extraneous header
# info, so that only the uuencoded portion remains. Files passed to
# sed must be passed in the proper order. Version 1 can be entered
# from the command line; version 2 can be made into an executable
# Unix shell script. (Modified from a script by Rahul Dhesi.)
sed '/^end/,/^begin/d' file1 file2 ... fileX | uudecode # vers. 1
sed '/^end/,/^begin/d' "$@" | uudecode # vers. 2
# sort paragraphs of file alphabetically. Paragraphs are separated by blank
# lines. GNU sed uses \v for vertical tab, or any unique char will do.
sed '/./{H;d;};x;s/\n/={NL}=/g' file | sort | sed '1s/={NL}=//;s/={NL}=/\n/g'
gsed '/./{H;d};x;y/\n/\v/' file | sort | sed '1s/\v//;y/\v/\n/'
# zip up each .TXT file individually, deleting the source file and
# setting the name of each .ZIP file to the basename of the .TXT file
# (under DOS: the "dir /b" switch returns bare filenames in all caps).
echo @echo off >zipup.bat
dir /b *.txt | sed "s/^\(.*\)\.TXT/pkzip -mo \1 \1.TXT/" >>zipup.bat
TYPICAL USE: Sed takes one or more editing commands and applies all of them, in sequence, to each line of input. After all the commands have been applied to the first input line, that line is output and a second input line is taken for processing, and the cycle repeats. The preceding examples assume that input comes from the standard input device (i.e, the console, normally this will be piped input). One or more filenames can be appended to the command line if the input does not come from stdin. Output is sent to stdout (the screen). Thus:
cat filename | sed '10q' # uses piped input sed '10q' filename # same effect, avoids a useless "cat" sed '10q' filename > newfile # redirects output to disk
QUOTING SYNTAX: The preceding examples use single quotes ('…') instead of double quotes ("…") to enclose editing commands, since sed is typically used on a Unix platform. Single quotes prevent the Unix shell from intrepreting the dollar sign ($) and backquotes (`…`), which are expanded by the shell if they are enclosed in double quotes. Users of the "csh" shell and derivatives will also need to quote the exclamation mark (!) with the backslash (i.e., \!) to properly run the examples listed above, even within single quotes. Versions of sed written for DOS invariably require double quotes ("…") instead of single quotes to enclose editing commands. USE OF '\t' IN sed SCRIPTS: For clarity in documentation, we have used the expression '\t' to indicate a tab character (0x09) in the scripts. However, most versions of sed do not recognize the '\t' abbreviation, so when typing these scripts from the command line, you should press the TAB key instead. '\t' is supported as a regular expression metacharacter in awk, perl, and HHsed, sedmod, and GNU sed v3.02.80. VERSIONS OF sed: Versions of sed do differ, and some slight syntax variation is to be expected. In particular, most do not support the use of labels (:name) or branch instructions (b,t) within editing commands, except at the end of those commands. We have used the syntax which will be portable to most users of sed, even though the popular GNU versions of sed allow a more succinct syntax. When the reader sees a fairly long command such as this:
sed -e '/AAA/b' -e '/BBB/b' -e '/CCC/b' -e d
it is heartening to know that GNU sed will let you reduce it to:
sed '/AAA/b;/BBB/b;/CCC/b;d' # or even sed '/AAA\|BBB\|CCC/b;d'
In addition, remember that while many versions of sed accept a command like "one s/RE1/RE2/", some do NOT allow "one! s/RE1/RE2/", which contains space before the 's'. Omit the space when typing the command. OPTIMIZING FOR SPEED: If execution speed needs to be increased (due to large input files or slow processors or hard disks), substitution will be executed more quickly if the "find" expression is specified before giving the "s/…/…/" instruction. Thus:
sed 's/foo/bar/g' filename # standard replace command sed '/foo/ s/foo/bar/g' filename # executes more quickly sed '/foo/ s//bar/g' filename # shorthand sed syntax
On line selection or deletion in which you only need to output lines from the first part of the file, a "quit" command (q) in the script will drastically reduce processing time for large files. Thus:
sed -n '45,50p' filename # print line nos. 45-50 of a file sed -n '51q;45,50p' filename # same, but executes much faster
6.7. Special applications
# remove nroff overstrikes (char, backspace) from man pages. The 'echo' command may need an -e switch if you use Unix System V or bash shell. sed "s/.`echo \\\b`//g" # double quotes required for Unix environment sed 's/.^H//g' # in bash/tcsh, press Ctrl-V and then Ctrl-H sed 's/.\x08//g' # hex expression for sed v1.5 # get Usenet/e-mail message header sed '/^$/q' # deletes everything after first blank line # get Usenet/e-mail message body sed '1,/^$/d' # deletes everything up to first blank line # get Subject header, but remove initial "Subject: " portion sed '/^Subject: */!d; s///;q' # get return address header sed '/^Reply-To:/q; /^From:/h; /./d;g;q' # parse out the address proper. Pulls out the e-mail address by itself from the 1-line return address header (see preceding script) sed 's/ *(.*)//; s/>.*//; s/.*[:<] *//' # add a leading angle bracket and space to each line (quote a message) sed 's/^/> /' # delete leading angle bracket & space from each line (unquote a message) sed 's/^> //' # remove most HTML tags (accommodates multiple-line tags) sed -e :a -e 's/<[^>]*>//g;/</N;//ba' # extract multi-part uuencoded binaries, removing extraneous header info, so that only the uuencoded portion remains. Files passed to sed must be passed in the proper order. Version 1 can be entered from the command line; version 2 can be made into an executable Unix shell script. (Modified from a script by Rahul Dhesi.) sed '/^end/,/^begin/d' file1 file2 ... fileX | uudecode # vers. 1 sed '/^end/,/^begin/d' "$@" | uudecode # vers. 2 # zip up each .TXT file individually, deleting the source file and setting the name of each .ZIP file to the basename of the .TXT file (under DOS: the "dir /b" switch returns bare filenames in all caps). echo @echo off >zipup.bat dir /b *.txt | sed "s/^\(.*\)\.TXT/pkzip -mo \1 \1.TXT/" >>zipup.bat
TYPICAL USE: Sed takes one or more editing commands and applies all of them, in sequence, to each line of input. After all the commands have been applied to the first input line, that line is output and a second input line is taken for processing, and the cycle repeats. The preceding examples assume that input comes from the standard input device (i.e, the console, normally this will be piped input). One or more filenames can be appended to the command line if the input does not come from stdin. Output is sent to stdout (the screen). Thus:
cat filename | sed '10q' # uses piped input sed '10q' filename # same effect, avoids a useless "cat" sed '10q' filename > newfile # redirects output to disk
For additional syntax instructions, including the way to apply editing commands from a disk file instead of the command line, consult "sed & awk, 2nd Edition," by Dale Dougherty and Arnold Robbins (O'Reilly, 1997; http://www.ora.com), "UNIX Text Processing," by Dale Dougherty and Tim O'Reilly (Hayden Books, 1987) or the tutorials by Mike Arst distributed in U-sedIT2.ZIP (many sites). To fully exploit the power of sed, one must understand "regular expressions." For this, see "Mastering Regular Expressions" by Jeffrey Friedl (O'Reilly, 1997). The manual ("man") pages on Unix systems may be helpful (try "man sed", "man regexp", or the subsection on regular expressions in "man ed"), but man pages are notoriously difficult. They are not written to teach sed use or regexps to first-time users, but as a reference text for those already acquainted with these tools. QUOTING SYNTAX: The preceding examples use single quotes ('…') instead of double quotes ("…") to enclose editing commands, since sed is typically used on a Unix platform. Single quotes prevent the Unix shell from intrepreting the dollar sign ($) and backquotes (`…`), which are expanded by the shell if they are enclosed in double quotes. Users of the "csh" shell and derivatives will also need to quote the exclamation mark (!) with the backslash (i.e., \!) to properly run the examples listed above, even within single quotes. Versions of sed written for DOS invariably require double quotes ("…") instead of single quotes to enclose editing commands. USE OF '\t' IN sed SCRIPTS: For clarity in documentation, we have used the expression '\t' to indicate a tab character (0x09) in the scripts. However, most versions of sed do not recognize the '\t' abbreviation, so when typing these scripts from the command line, you should press the TAB key instead. '\t' is supported as a regular expression metacharacter in awk, perl, and HHsed, sedmod, and GNU sed v3.02.80. VERSIONS OF sed: Versions of sed do differ, and some slight syntax variation is to be expected. In particular, most do not support the use of labels (:name) or branch instructions (b,t) within editing commands, except at the end of those commands. We have used the syntax which will be portable to most users of sed, even though the popular GNU versions of sed allow a more succinct syntax. When the reader sees a fairly long command such as this:
sed -e '/AAA/b' -e '/BBB/b' -e '/CCC/b' -e d
it is heartening to know that GNU sed will let you reduce it to:
sed '/AAA/b;/BBB/b;/CCC/b;d' # or even sed '/AAA\|BBB\|CCC/b;d'
In addition, remember that while many versions of sed accept a command like "one s/RE1/RE2/", some do NOT allow "one! s/RE1/RE2/", which contains space before the 's'. Omit the space when typing the command. OPTIMIZING FOR SPEED: If execution speed needs to be increased (due to large input files or slow processors or hard disks), substitution will be executed more quickly if the "find" expression is specified before giving the "s/…/…/" instruction. Thus:
sed 's/foo/bar/g' filename # standard replace command sed '/foo/ s/foo/bar/g' filename # executes more quickly sed '/foo/ s//bar/g' filename # shorthand sed syntax
On line selection or deletion in which you only need to output lines from the first part of the file, a "quit" command (q) in the script will drastically reduce processing time for large files. Thus:
sed -n '45,50p' filename # print line nos. 45-50 of a file sed -n '51q;45,50p' filename # same, but executes much faster
If you have any additional scripts to contribute or if you find errors in this document, please send e-mail to the compiler. Indicate the version of sed you used, the operating system it was compiled for, and the nature of the problem. Various scripts in this file were written or contributed by: Al Aab <af137@freenet.toronto.on.ca> # "seders" list moderator Edgar Allen <era@sky.net> # various Yiorgos Adamopoulos <adamo@softlab.ece.ntua.gr> Dale Dougherty <dale@songline.com> # author of "sed & awk" Carlos Duarte <cdua@algos.inesc.pt> # author of "do it with sed" Eric Pement <pemente@northpark.edu> # author of this document Ken Pizzini <ken@halcyon.com> # author of GNU sed v3.02 S.G. Ravenhall <stew.ravenhall@totalise.co.uk> # great de-html script Greg Ubben <gsu@romulus.ncsc.mil> # many contributions & much help
6.8. More
# 1.Double space infile and send the output to outfile
sed G < infile > outfile
# I use the input/output notation shown above. It is appropriate in many, if not all, cases to leave out the less than sign, e.g., sed G infile > outfile
# 2.Double space a file which already has blank lines in it. Output file should contain no more than one blank line between lines of text.
sed '/^$/d;G' < infile > outfile
# 3.Triple space a file
sed 'G;G' < infile > outfile
# 4.Undo double-spacing (assumes even-numbered lines are always blank)
sed 'n;d' < infile > outfile
# 5.Insert a blank line above every line which matches regex ("regex" represents a regular expression)
sed '/regex/{x;p;x;}' < infile > outfile
# 6.Print the line immediately before regex, but not the line containing regex
sed -n '/regexp/{g;1!p;};h' < infile > outfile
# 7.Print the line immediately after regex, but not the line containing regex
sed -n '/regexp/{n;p;}' < infile > outfile
# 8.Insert a blank line below every line which matches regex
sed '/regex/G' < infile > outfile
# 9.Insert a blank line above and below every line which matches regex
sed '/regex/{x;p;x;G;}' < infile > outfile
# 10.Convert DOS newlines (CR/LF) to Unix format
sed 's/^M$//' < infile > outfile # in bash/tcsh, to get ^M press Ctrl-V then Ctrl-M
# 11.Print only those lines matching the regular expression-similar to grep
sed -n '/some_word/p' infile
sed '/some_word/!d'
# 12.Print those lines that do not match the regular expression-similar to grep -v
sed -n '/regexp/!p'
sed '/regexp/d'
# 13.Skip the first two lines (start at line 3) and then alternate between printing 5 lines and skipping 3 for the entire file
sed -n '3,${p;n;p;n;p;n;p;n;p;n;n;n;}' < infile > outfile
# Notice that there are five p's in the sequence, representing the five lines to print. The three lines to skip between each set of lines to print are represented by the n;n;n; at the end of the sequence.
# 14.Delete trailing whitespace (spaces, tabs) from end of each line
sed 's/[ \t]*$//' < infile > outfile
# 15.Substitute (find and replace) foo with bar on each line
sed 's/foo/bar/' < infile > outfile # replaces only 1st instance in a line
sed 's/foo/bar/4' < infile > outfile # replaces only 4th instance in a line
sed 's/foo/bar/g' < infile > outfile # replaces ALL instances in a line
# 16.Replace each occurrence of the hexadecimal character 92 with an apostrophe:
sed s/\x92/'/g" < old_file.txt > new_file.txt
# 17.Print section of file between two regular expressions (inclusive)
sed -n '/regex1/,/regex1/p' < old_file.txt > new_file.txt
# 18.Combine the line containing REGEX with the line that follows it
sed -e 'N' -e 's/REGEX\n/REGEX/' < old_file.txt > new_file.txt
7. Quines
TBD
8. Exercises
Create a sed script file for each task listed below. Use the -f option on the sed command and I/O UNIX redirection to create a new file based on the sed.input.file available in the posting directory. Name each of the sed scripts #.sed.script where the #-sign refers to the task number given below.
- Make a new file named 1.sed which has only lines 1,2,3,4 and 5 from the original input file.
- Make a new file named 2.sed which has only lines 10, 12, and 14 from the original input file.
- Make a new file named 3.sed which has only the lines that contain the word "line" from the original input file.
- Make a new file named 4.sed which has only the lines that contain a numeric character (0-9) from the original input file.
- Make a new file named 5.sed which contains all of the lines from the original input file, but anytime the word "line" appears it should be exchanged with the word "entry". Also make sure that if "Line" appears it is replaced by "Entry".
- Make a new file named 6.sed which contains all of the lines that do not contain a numeric character.
- Make a new file named 7.sed which replaces any line with a numeric character with a line of three X's "XXX"
- Make a new file named 8.sed which adds a new line (three X's) before each line that contains a numeric character.
- Make a new file named 9.cap.sed which contains all lines that have a capital alphabetical character in the same script that puts all lines that do not have a capital alphabetical character into the file named 9.nocap.sed.
- Make a new file named 10.sed which takes any numeric character and writes it out twice in a row (twice for each one time it appears in the input file).