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.

Advertisement

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
    path-without-comma
    :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))))

    (progn
    (transform-name-file “20170804–name.data” “20170804–name.txt”)
    (values (com.informatimago.common-lisp.cesarum.file:string-list-text-file-contents “20170804–name.data”)
    (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: https://app.box.com/s/121nemup56e4n8au3p0mi8samfr5v14x
    Code screenshot: https://app.box.com/s/uekpewsz173j0k2a76lg63xlgirgaalb

    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:

WordPress.com Logo

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

Facebook photo

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

Connecting to %s

%d bloggers like this: