Remove last space in a string?

I have a customer file now and would like to separate the names into two cells in a spreadsheet. Here is my data as an example:

SHAWN R KEEGAN
shawn r scroggin
Shawn Regan
Shawn Reilly

The first two have the middle initial so I'd like to include them in the "first name" field and the last name in the "last name" field. So what I need is a script to suck in the names in a text file and replace the last space in each line with a pipe so my data would look like this when converted:

SHAWN R|KEEGAN
shawn r|scroggin
Shawn|Regan
Shawn|Reilly

Best option please? I've searched the forum here and not found a way to do this specific example.

Easy, the bourne shell read builtin splits on IFS (which is by default whitespace) and trims. [edit] fixed to arrange middle initials properly.

#!/bin/sh

while read A B C
do
        if [ ! -z "${C} ] 
        then
                echo "${A} ${B}|${C}"
        else
                echo "${A}|${B}"
        fi
        C=""
done < input > output

Sorry, I should have specified but I only really know Perl. Can you put it in layman's terms using Perl? :smiley:

Hi,

Using 'perl':

$ perl -lpe 's/^(.*)\s+(.*)$/\1|\2/' infile

Regards,
Birei

Consider this your introduction to a scripting language that doesn't resemble line noise, then. :wink:

For the record :slight_smile:
Using sed:

tukuyomi@debian:~/unix.com$ cat name
SHAWN R KEEGAN
shawn r scroggin
Shawn Regan
Shawn Reilly
tukuyomi@debian:~/unix.com$ sed -r 's/(.*) (.*)$/\1|\2/' name
SHAWN R|KEEGAN
shawn r|scroggin
Shawn|Regan
Shawn|Reilly
awk '$NF="|"$NF' infile
1 Like
perl -pe 's/ (?=[^ ]+$)/|/' file
sed 's/ \([^ ]*\)$/|\1/' file
awk '{s=$NF;NF--;$0=$0"|"s}1' file
1 Like

alternate with sed..

sed 's/ [^ ]*$/ |&/'

That will introduce spaces, no?

yes :smiley: nice catch. Im trying to modify the command..

I tried this and it simply added the pipe at the end of each customer record as follows:

customer.txt file includes:

SHAWN R KEEGAN
shawn r scroggin
Shawn Regan
Shawn Reilly

Script:

#!/usr/bin/perl

$file = '/home/www/misc/customers.txt';

open(FH_TMP,"<","$file");
open(OUT,">>",tmpfile);
while (my $line = <FH_TMP>)
{
# chomp ($line);
$line =~ s/^(.*)\s+(.*)$/\1|\2/;
print OUT $line;
}
close(FH_TMP);
close(OUT);

Output to tmpfile is:

SHAWN R KEEGAN|shawn r scroggin|Shawn Regan|Shawn Reilly|

Desired output is:

SHAWN R|KEEGAN
shawn r|scroggin
Shawn|Regan
Shawn|Reilly