Last Name Comma First Name

August 4, 2017

We use sed to reformat the file:

$ sed 's/\([^,]*\), *\([^,]*\),* *\(.*\)/\2 \1 \3/;s/ *$//'
Holmes, Sherlock
Sherlock Holmes
Smith, John, Jr
John Smith Jr

The sed command has two clauses separated by a semicolon. The first clause parses the input into three fields separated by commas, each comma optionally followed by spaces; the escaped parentheses surround pieces of the line, the three names, saving them to be inserted in the output with the escaped digits. The second clause removes the trailing white space inserted by the space between \1 and \3. The two lines with commas are typed by the user, the two lines without commas are responses from sed.

Ideone doesn’t provide sed, so we can’t show the solution in action.

Pages: 1 2

4 Responses to “Last Name Comma First Name”

  1. perl -p -e 's{([^,]*),\s*([^,]*)(?:,\s*([^,]*?))?\n}{$2 $1 $3\n}'

    It’s a perl 1-liner – but a bit nasty – probably made this harder than required – as it can cope with no Sr/Jr/ordinal

  2. [sourcecode lang="css"]

    (ql:quickload :com.informatimago.common-lisp.cesarum)
    (ql:quickload :split-sequence)

    (defun transform-name-file (path-with-comma path-without-comma)
    (setf (com.informatimago.common-lisp.cesarum.file:string-list-text-file-contents
    :if-does-not-exist :create
    :if-exists :supersede)
    (mapcar (lambda (line)
    (destructuring-bind (name firstname &optional numeral)
    (split-sequence:split-sequence #\, line)
    (let ((name (string-trim ” ” name))
    (firstname (string-trim ” ” firstname))
    (numeral (and numeral (string-trim ” ” numeral))))
    (format nil “~A ~A~@[ ~A~]” firstname name numeral))))
    (com.informatimago.common-lisp.cesarum.file:string-list-text-file-contents path-with-comma))))

    (transform-name-file “20170804–” “20170804–name.txt”)
    (values (com.informatimago.common-lisp.cesarum.file:string-list-text-file-contents “20170804–”)
    (com.informatimago.common-lisp.cesarum.file:string-list-text-file-contents “20170804–name.txt”)))
    –> (“McCarthy,John” “Bush,Georges,Jr.” “Gates, Bill, III” “Newton, John”)
    (“John McCarthy” “Georges Bush Jr.” “Bill Gates III” “John Newton”)

    [/sourcecode lang="css"]

  3. Zack said

    Julia implementation.

    Data screenshot:
    Code screenshot:

    I’d post everything here, but it seems that I can’t get the formating right when I include code in this site.

    Have a nice weekend!

  4. steve M said

    This is doable in plain old bash

    export IFS=,
    while read $last $first $num
    do echo $first $last $num|xargs
    done <file

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: