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 CTRL-D
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.
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
[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"]
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!
This is doable in plain old bash
export IFS=,
while read $last $first $num
do echo $first $last $num|xargs
done <file