LinuxCommandLibrary

caret

Shell history substitution and regex anchor character

TLDR

Quick substitution on last command

$ ^[old]^[new]
copy
Repeat last command replacing text
$ ^typo^fixed
copy
Start of line anchor (regex)
$ grep "^start" [file]
copy
Negation in character class (regex)
$ grep "[^0-9]" [file]
copy

SYNOPSIS

^old^new[^]

DESCRIPTION

^ in shell has multiple meanings:
History substitution: ^old^new is a shortcut for !!:s/old/new/, replacing text in the previous command. Quick fix for typos without retyping.
Regular expression anchor: ^ matches the start of a line. ^hello matches lines starting with "hello".
Character class negation: [^abc] matches any character except a, b, or c.
Exponentiation: In $((...)) and some languages, ^ may be XOR or exponent (use ******** in bash for exponent).

HISTORY SUBSTITUTION

^old^new

Replace first occurrence of "old" with "new" in previous command and execute
^old^new^
Same, trailing ^ is optional
!!:s/old/new/
Equivalent using full history syntax

CAVEATS

^old^new only replaces the first occurrence. For global replacement, use !!:gs/old/new/.
In some shells/contexts, ^ may need escaping or behave differently.
The caret substitution must be at the start of the command line.

SEE ALSO

bash(1), history(1), grep(1), sed(1)

> TERMINAL_GEAR

Curated for the Linux community

Copied to clipboard

> TERMINAL_GEAR

Curated for the Linux community