2

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
  • 1
    Post multiple lines of your file and desired result. – Cyrus Oct 18 '14 at 17:04
  • @cyrus, please see above – Justin Oct 18 '14 at 17:07
  • That's dummy data right? Not a good idea to put real data in a public question. – Seth Oct 18 '14 at 17:30
  • 1
    With names like "Betty Boop," I can assure you its fake :-) – Justin Oct 18 '14 at 17:32
  • Is necessary that it should be sed? – Braiam Oct 19 '14 at 1:10
9

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

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.