>_ IzzyLab

Hands-on task

This task is step 11 of the course “sed: the stream editor”

sed: reordering via a backreference

medium~5 min

In /root/in.txt there are lines of the form First Last. Rearrange them into the format Last, First (with a comma and a space). Write the result to /root/out.txt.

What you'll practise:
  • sed
  • backreference
  • capture groups
  • sed -E
  • reordering

Topic breakdown

To swap parts of a line, you first "capture" them with groups — parentheses in the regex — and on the right side of the substitution you refer to the captured text by group number (\1, \2, etc.); that's what a backreference is. With the extended syntax (sed -E) parentheses work as groups without escaping. Having described a pattern with several groups, in the replacement you output them in the right order with the right separator.

What's checked

  1. first and last name swapped with a comma

What it looks like