Flags

g

Using backreferences in a sed command allows you to reuse parts of the matched pattern in the replacement string. This is useful for tasks like reordering matched groups or adding additional text to specific parts of the match.

Here’s a general breakdown:

  1. Capturing groups: Use parentheses \( ... \) to capture parts of the match in the search pattern. These are assigned numbers based on their position, starting from \1.
  2. Referencing groups: Use \1, \2, etc., in the replacement string to refer to the corresponding captured groups.

Example: Swap First and Last Words

Suppose you want to swap the first and last words of a string:

echo "Hello world" | sed 's/^\(.*\) \(.*\)$/\2 \1/'

Explanation:

  • ^\(.*\) \(.*\)$: Captures everything before the space as \1 and everything after the space as \2.
  • \2 \1: Swaps the two groups in the replacement string.

Example: Add Text Around Matched Groups

If you want to wrap matched words with tags:

echo "word" | sed 's/\(word\)/<b>\1<\/b>/'

Explanation:

  • \(word\): Matches and captures the word “word” as \1.
  • <b>\1<\/b>: Wraps the captured group in <b> and </b> tags.

Example: Reformat Dates

Convert a date from YYYY-MM-DD to DD-MM-YYYY:

echo "2024-12-07" | sed 's/^\([0-9]\{4\}\)-\([0-9]\{2\}\)-\([0-9]\{2\}\)$/\3-\2-\1/'

Explanation:

  • \([0-9]\{4\}\) captures the year as \1.
  • \([0-9]\{2\}\) captures the month as \2.
  • \([0-9]\{2\}\) captures the day as \3.
  • \3-\2-\1 rearranges the groups.

Notes

  • Always escape the parentheses \( and \) in sed to denote capturing groups.
  • Use -r (or --regexp-extended) if you want to avoid escaping parentheses in some versions of sed.

Let me know if you need help with a specific substitution!