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

Wabbit

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:

  \3\2\1

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.

Geek Guide
The DevOps Toolbox

Tools and Technologies for Scale and Reliability
by Linux Journal Editor Bill Childers

Get your free copy today

Sponsored by IBM

Webcast
8 Signs You're Beyond Cron

Scheduling Crontabs With an Enterprise Scheduler
On Demand
Moderated by Linux Journal Contributor Mike Diehl

Sign up and watch now

Sponsored by Skybot