Ubuntu – Sed Script – Reversing names

sed

I have a text file with several names that are arranged with the First name first, and the Last name second. How can I use Sed to reverse this order of names so that the Last name is first, and the First name is last?

For example I have lines like below

Steve Blenheim:238-923-7366:95 Latham Lane, Easton, PA 83755:11/12/56:20300
Betty Boop:245-836-8357:635 Cutesy Lane, Hollywood, CA 91464:6/23/23:14500
Igor Chevsky:385-375-8395:3567 Populus Place, Caldwell, NJ 23875:6/18/68:23400

I would like them to look like

Blenheim Steve:238-923-7366:95 Latham Lane, Easton, PA 83755:11/12/56:20300
Boop Betty:245-836-8357:635 Cutesy Lane, Hollywood, CA 91464:6/23/23:14500
Chevsky Igor:385-375-8395:3567 Populus Place, Caldwell, NJ 23875:6/18/68:23400

Best Answer

Through sed,

$ sed 's/^\([^ ]*\) \([^:]*\)/\2 \1/' file
Blenheim Steve:238-923-7366:95 Latham Lane, Easton, PA 83755:11/12/56:20300
Boop Betty:245-836-8357:635 Cutesy Lane, Hollywood, CA 91464:6/23/23:14500
Chevsky Igor:385-375-8395:3567 Populus Place, Caldwell, NJ 23875:6/18/68:23400

Explanation:

  • ^ Asserts that we are at the start.
  • \(...\) Default sed use BRE(Basic Regular Expressions). In BRE, capturing groups are mentioned by \(-> start of a capturing group, \) -> end of a capturing group.
  • [^ ]* Matches any character but not of space character zero or more times.
  • So the combined form \([^ ]*\) would capture the string zero or more non-space characters . That is the first word.
  • Matches a space.
  • \([^:]*\) Captures any character but not of : zero or more times.
  • In the replacement part, refer the group index 2 as first and index 1 as second. So that the matched would be printed in reversed form.

Through Perl,

perl -pe 's/^(\S+)\s([^:]+)/\2 \1/' file
Related Question