Note ## removes longest prefix match, # removes shortest. %% removes longest suffix, % removes shortest. These are pure Bash operations (no subprocess), so they are much faster than calling sed or basename in a loop.
// 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.
Frequently asked questions
How does Bash & Linux handle string replace?
This task is covered in 3 stacks on this page: Bash & Linux, JavaScript, Regular Expressions. The "String Operations" snippet in Bash & Linux uses `${#string} # length`.
Which command does the Bash & Linux example use?
The "String Operations" snippet uses `${#string} # length`, from the Bash Scripting section of the Bash & Linux cheat sheet.
Which stacks cover "string replace" on this page?
Bash & Linux, JavaScript, Regular Expressions. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "String Operations": ## removes longest prefix match, # removes shortest. %% removes longest suffix, % removes shortest. These are pure Bash operations (no subprocess), so they are much faster than calling sed or basename in a loop.