Replace text

3 snippets across 3 stacks - Bash & Linux, Python, SQL

SHBash & Linux

Stream Editor for Find & Replace

SH · Text Processing
Syntax
sed [options] 's/pattern/replacement/flags' file
Example
sed 's/localhost/0.0.0.0/g' config.ini
sed -i.bak 's/v1\.2/v1.3/g' version.txt
sed -n '10,20p' access.log
sed '/^$/d' notes.txt

Note -i edits in place. -i.bak creates a backup before editing (strongly recommended). g flag replaces all occurrences on a line, not just the first. -n suppresses default output; use with p to print specific lines. /d deletes matched lines.

PYPython

Common String Methods

PY · Strings
Syntax
str.method()
Example
email = "  [email protected]  "
print(email.strip().lower())
print("hello world".title())
print("python".startswith("py"))
print("2026-04-04".replace("-", "/"))
Output
[email protected]
Hello World
True
2026/04/04

Note String methods always return new strings since strings are immutable. Chain methods for compact transformations.

SQLSQL

REPLACE

SQL · String Functions
Syntax
REPLACE(string, search, replacement)
Example
SELECT
  REPLACE(phone, '-', '') AS digits_only,
  REPLACE(product_name, 'V1', 'V2') AS updated_name
FROM products;
Output
-- digits_only | updated_name
-- 2065551234  | Widget V2 Pro

Note REPLACE is case-sensitive in PostgreSQL and MySQL. It replaces all occurrences, not just the first one. For regex-based replacement in PostgreSQL, use REGEXP_REPLACE.

Frequently asked questions

How do you replace text?
This task is covered in 3 stacks on this page: Bash & Linux, Python, SQL. The "Stream Editor for Find & Replace" snippet in Bash & Linux uses `sed [options] 's/pattern/replacement/flags' file`.
Which command does the Bash & Linux example use?
The "Stream Editor for Find & Replace" snippet uses `sed [options] 's/pattern/replacement/flags' file`, from the Text Processing section of the Bash & Linux cheat sheet.
Which stacks cover "replace text" on this page?
Bash & Linux, Python, SQL. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Stream Editor for Find & Replace": -i edits in place. -i.bak creates a backup before editing (strongly recommended). g flag replaces all occurrences on a line, not just the first. -n suppresses default output; use with p to print specific lines. /d deletes matched lines.