Last Name Comma First Name

August 4, 2017

Today’s task is simple:

You are given a file containing one name per line in the format last name comma first name, optionally followed by another comma and a numeral (like Sr., or Jr., or IV), and are convert it to a file containing the names, one name per line, in the format first name, last name and numeral with no commas. You may assume the input is correctly formatted, with optional spaces after each of the two commas.

Your task is to convert a file of names to the correct format. When you are finished, you are welcome to read a suggested solution, or to post your own solution or discuss the exercise in the comments below.


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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: