Skip to content
Latchkey

sed s/// Flags: g, i, p, and Numbered

The flags after the final slash of an s command decide how many matches change and whether the line prints.

A bare s/// only touches the first match per line. The g, i, p, and numeric flags extend that to all matches, ignore case, print, or target one occurrence.

What it does

Flags trail the closing delimiter of the s command. g replaces every match on the line, i (or I in GNU) makes the pattern case-insensitive, p prints the result, and a number N replaces only the Nth match. Combine N with g to replace the Nth and all that follow.

Common usage

Terminal
echo "a a a" | sed 's/a/b/g'      # b b b
echo "Foo foo" | sed 's/foo/bar/gi' # bar bar
echo "x x x" | sed 's/x/y/2'        # x y x
echo "x x x" | sed 's/x/y/2g'       # x y y

Options

FlagWhat it does
gReplace all matches on the line, not just the first
i or ICase-insensitive matching (I is the GNU form)
pPrint the line; pair with -n to print only changed lines
NReplace only the Nth match on the line
NgReplace the Nth match and every match after it
eGNU only: execute the result as a command

In CI

GNU sed accepts both i and I as the case-insensitive flag, while BSD sed on macOS accepts only I in the s flags. If a macOS runner reports an error on s/foo/bar/i, switch the flag to I or add a separate address.

Common errors in CI

sed: -e expression #1, char N: unknown option to s' means an unsupported flag letter, often a lowercase i on BSD sed or a stray character after the flags. sed: -e expression #1, char N: multiple g' options to `s' command means g was written twice.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →