-------------------------------------------------- -----------------------
Handy One-Liners For Sed (Unix Stream Editor) APR. 26, 2004
Compiled by Eric PEMENT - PEMENTE [AT] Northpark [Dot] EDU VERSION 5.4
Latest Version of this File is Usually AT:
http://sed.sourceforge.net/sed1line.txt
http://www.student.northpark.edu/pemente/sed/sed1line.txt
This File Is Also Available in Portuguese At:
http://www.lrv.ufsc.br/wmaker/sed_ptbr.html
File spacing:
# Double Space a file
Sed G
# 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'
# TrIPLE SPACE A File
Sed 'g; g'
# undo double-spacing (Assumes Even-Numbeled Lines Are Always Blank)
Sed 'n; 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'
# INSERT A Blank Line Above and Below Every Line Which Matches "Regex"
Sed '/ regex / {x; p; x; g;}'
Numbering:
# Number Each line of a file (Simple LEFT Alignment). Using A Tab (SeeE
# Note ON '/ T' at End of File Instead of Space Will Preserve Margins.
Sed = filename | SED 'N; S / / N // T /'
# 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 '$ ='
Text Conversion and Substitution:
# In Unix Environment: Convert Dos NewLines (CR / L) To Unix Formatsed 'S /. $/' # Assumes That All Lines End With CR / LF
SED 'S / ^ m $ //' # in Bash / TCSH, Press Ctrl-V Then Ctrl-M
Sed 's // x0d $ //' # GSED 3.02.80, But Top Script IS Easier
# 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
# 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.
# Cannot Be Done with other dos version of sed. Use "TR" INSTEAD.
SED "S // R //" Infile> Outfile # unxutils sed v4.0.7 or higher
Tr -D / R
# 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 Widthsed -e: a -e 's / ^./ {1,78 /} $ / & /; ta' # set at 78 Plus 1 Space
# center all text in the middle of 79-colorn width. in normal 1,
# Spaces at the beginning of the line area significant, and trailing
# Spaces Are Appended At the end of the line. in Method 2, Spaces At
# t Beginning of the line area 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
# Substitution (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-la cast case
Sed 's //(.*/) foo // 1bar /' # Replace ONLY THE LAST CASE
# Substitution "foo" with "bar" Only for Lines Which Contain "BAZ"
Sed '/ baz / s / foo / bar / g'
# Substitution "Foo" with "bar" Except for Lines Which Contain "Baz"
Sed '/ baz /! s / foo / bar / g'
# Change "scarlet" or "ruby" or "put" 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 / /'
#hen a line ends with a backslash, append the next line to it
Sed -e: a -e '/// $ / n; sn //; ta'
# ify # 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 comms to numbers with Decimal Points and Minus Signs (GNU SED)
Gsed ': 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;' # taher seds
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 '$;; 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 Only Lines Which Match Regular Expression (Emulates "GREP")
Sed -n '/ regexp / p' # method 1sed '/ 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
# ionure 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 bb and ccc (in any order)
Sed '/ aaa /! d; / bbb /! d; / ccc /! d'
# GREP for aaa and bb and ccc (in That Order)
Sed '/aa.*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 IT Contains AAA (Blank Lines Separate Paragraphs)
# HHSED V1.5 MUST INSERT A 'G;' After 'X;' In The Next 3 Scripts Below
Sed -e '/./ (}' -e 'x; / aaa /! d;'
# Print Paragraph If IT Contains AAA and BBB AND CCC (in any ORDER)
Sed -e '/./ (}' -e 'x; / aaa /! d; / bbb /! d; / ccc /! d'
# Print Paragraph if IT Contains aaa or bbb or ccc
Sed -e '/./ (}' -e 'x; / aaa / b' -E '/ bbb / b' -e '/ ccc / b'-E d
Gsed '/./ / (} (}}; }/aaa/|bbb/|ccc/b;d' # gnu Sed ONLY
# print Only Lines of 65 Characters Or LONGERSED-N '/^./{ 65/On }/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 Online 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
Selective Deletion of Certain Lines:
# Print All of File Except Section BetWeen 2 Regular Expressions
Sed '/ iowa /, / montana / d'
# delete duplicate, Connecutive Lines from a file (Emulate "Uniq").
# First Line in a set of duplicate Lines IS Kept, REST ARE DELETED.
Sed '$! n; /^/ (.*/ )/n/1 or $/p; d'
# delete duplicate, Nonconsecutive Lines from a file. BeWare Not to 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 (Emulate "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 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 '/.///0 $ !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 '/./,!
# 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;}'
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 / .`` /// 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' # hx expression for sed v1.5 # get.com / 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 / (: <] * ///'
# | add a leading angle bracket and space to each line (quote a message)
Sed 's / ^ /> /'
# delete Leading Angle Bracket & Space from Each Line (Unsote a Message)
Sed 's / ^> //'
# REMOVE MOST HTML TAGS (Accommodates Multiple-Line Tags)
Sed -e: a -e 's / <[^>] *> // g; / n; // ba'
# xtract 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 DELETIN
# 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.battypical 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 be be appended to the commit line ing the input does
NOTPUT 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 commit 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 area not written to
TEACH SED USE OR Regexps to First-Time Users, But As a Reference TextFor Those Already Acquainted with these Tools.
Quoting syntax: The preceding example 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 intReting the dollar sign ($) and backquotes
(`...`), Which is expanded by the shelliff f.
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
("...") INSTET OF SINGLE Quotes to Enclose Editing Commands.
Use of '/ t' in sed scripts: for clarity in documentation, We Have Used
The expression '/ t' to indeicate 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 Difer, And Some Slight Syntax
VARIATION IS To Be Expected. in particular, MOT 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 useed the syntax
Which Will Be Portable To Most Uses 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 '/ ccc / b' -e Dit 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 Version 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 type.
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 Dravestical 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 controlle 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 is time, ip
The Nature of The Problem. Various Scripts in this file werewrew
OR Controluted by:
Al Aab
Edgar Allen
Dale Dougherty
Carlos duarte
Eric pement
Ken Pizzini
S.g. Ravenhall
Greg Ubben
-------------------------------------------------- -----------------------