SED substitutions

The format for the substitute command is as follows:

    [address1[ ,address2]]s/pattern/replacement/[flags] 

The flags can be any of the following:

  • n replace nth instance of pattern with replacement
  • g replace all instances of pattern with replacement
  • p write pattern space to STDOUT if a successful substitution takes place
  • w file Write the pattern space to file if a successful substitution takes place
  • i match REGEXP in a case-insensitive manner.

We can use different delimiters ( one of @ % ; : ) instead of /. If no flags are specified the first match on the line is replaced. note that we will almost always use the s command with either the g flag or no flag at all.

If one address is given, then the substitution is applied to lines containing that address. An address can be either a regular expression enclosed by forward slashes /regex/ , or a line number . The $ symbol can be used in place of a line number to denote the last line. If two addresses are given separated by a comma, then the substitution is applied to all lines between the two lines that match the pattern.

Example 1: substitute only third occurrence of a word sed s//3

$ sed 's/Data/Big-Data/3' datafile

Example 2: print and write to a file sed s//gpw

$ sed -n 's/Data/Big-Data/gpw output' datafile

Some important SED options

Option:-n, --quiet or --silent

The "-n" option will not print anything unless an explicit request to print is found:

sed -n 's/PATTERN/&/p' file

Option: -e

Combines multiple commands:

sed -e 's/a/A/' -e 's/b/B/' file

Option: -f

If you have a large number of sed commands, you can put them into a file and use

sed -f sedscript file

Option: -r

Extended regular expressions (ERE) have more power, but SED them normal characters. Therefore you must explicitly enable this extension with a command line option.

% echo "123 abc" | sed -r 's/[0-9]+/& &/'
123 123 abc

Option: -i

Substitutions a re performed in-place, on the file which was fed to SED:

sed -i 's/^/\t/' *.txt

Get hands-on with 1200+ tech skills courses.