Find and replace

4 snippets across 4 stacks — Bash & Linux, JavaScript, Regular Expressions, 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.

JSJavaScript

Replacing Text

JS · Strings
syntax
str.replace(search, replacement)
str.replaceAll(search, replacement)
example
const template = "Hello {name}, welcome to {place}!";
const filled = template
  .replace("{name}", "Ava")
  .replace("{place}", "Berlin");
console.log(filled);

const csv = "a,b,c,d";
console.log(csv.replaceAll(",", " | "));
output
"Hello Ava, welcome to Berlin!"
"a | b | c | d"

Note replace() only swaps the first match unless you use a regex with the /g flag. replaceAll() replaces every occurrence.

RXRegular Expressions

JS: replace() / replaceAll()

RX · String Operations with Regex
syntax
string.replace(/pattern/, replacement)
string.replaceAll(/pattern/g, replacement)
example
// Backreference in replacement
'John Smith'.replace(/(\w+) (\w+)/, '$2, $1')
// Function replacement
'hello'.replace(/\w/g, c => c.toUpperCase())
output
"Smith, John"
"HELLO"

Note In the replacement string, $1 $2 refer to captured groups, $& is the full match, $` is before-match, $' is after-match. Use a function for dynamic replacements. replaceAll() requires the g flag on regex arguments.

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.