User Tools

Site Tools


sed:introduction

SED - Introduction

Typical Usage

Example UsageComment
cat filename | sed '10q'Uses piped input.
sed '10q' filenameSame effect, avoids a useless “cat”.
sed '10q' filename > newfileRedirects 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 interpreting the dollar sign ($) and back-quotes (`…`), 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 this 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.

NOTE: '\t' is supported as a regular expression metacharacter in awk, perl, and HHsed, sedmod, and GNU sed v3.02.80.


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
sed/introduction.txt · Last modified: 2022/06/14 08:20 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki