Searching and replacing text

Fish Shell:
Searching and replacing text

How to:

Let’s change all instances of ‘cat’ to ‘dog’ in a string.

echo "One cat, two cats, three cats." | string replace -a 'cat' 'dog'

Sample output:

One dog, two dogs, three dogs.

Replacing text in a file named pets.txt:

string replace -a 'cat' 'dog' < pets.txt > updated_pets.txt

Using variables for patterns:

set old "cat"
set new "dog"
string replace -a $old $new < pets.txt > updated_pets.txt

Deep Dive

Search and replace has been in text editors since the early days. Think sed for stream editing in Unix — that’s old school cool. Fish takes this further, making it simpler with the string command. No more regex headaches unless you want them. Alternatives? Sure: sed, awk, Perl scripts, even vim macros. But Fish’s string command is elegant and less prone to errors for the common cases.

See Also: