Need some help with the sed command

Alright here is what I'm trying to do. I'm trying to use the sed command to sort a field so it comes out like lastname firstname

so say if I have something like this

Bugs Bunny:603-479-5498:12/9/09/:20300

and I want it to come out like this

Bunny Bugs:603-479-5498:12/9/09/:20300

how would I do that using sed? Now I know that I could do it perhaps using awk, but please tell me how to do it with sed


Mitch Frazier's picture

Something like this should do it:

  sed -e 's/\(^[^ ]*\)\([ \t]*\)\([^:]*\)/\3\2\1/'< INPUTFILE

The expression contains three capture groups:

  \(^[^ ]*\)
  \([ \t]*\)

The first starts at the beginning of the line and captures everything except spaces (ie the first word/name). The second captures all the whitespace between the names. The third captures everything except colons (ie the second word/name). The replacement simply rearranges the order of the items:


If you don't care about preserving the spacing, or if you want to normalize the spacing you could simplify it slightly to:

  sed -e 's/\(^[^ ]*\)[ \t]\([^:]*\)/\2 \1/'< INPUTFILE

Mitch Frazier is an Associate Editor for Linux Journal.

Free Dummies Books
Continuous Engineering


  • What continuous engineering is
  • How to continuously improve complex product designs
  • How to anticipate and respond to markets and clients
  • How to get the most out of your engineering resources

Get your free book now

Sponsored by IBM

Free Dummies Books
Service Virtualization

Learn to:

  • Define service virtualization
  • Select the most beneficial services to virtualize
  • Improve your traditional approach to testing
  • Deliver higher-quality software faster

Get your free book now

Sponsored by IBM