Operating System - HP-UX
1833875 Members
1872 Online
110063 Solutions
New Discussion

Need to grep for first initial and lastname

 
SOLVED
Go to solution
Allanm
Super Advisor

Need to grep for first initial and lastname

I have a list of username in the form of -

firstname_lastname and I need the date in this form -

f_lastname

How shall I go about getting this.

Thanks,
Allan.
5 REPLIES 5
Allanm
Super Advisor

Re: Need to grep for first initial and lastname

date=data
Matti_Kurkela
Honored Contributor
Solution

Re: Need to grep for first initial and lastname

One username on each line, and nothing else on the lines?

sed -e 's/^\(.\)[^_]*_\(.*\)$/\1_\2/g' < firstname_lastname.txt > f_lastname.txt

This is a regular expression, which tends to look a bit cryptic. (Someone has said they tend to be Write-Only.)

So here's it split into meaningful parts:

s/ ... / ... /g = the global search-and-replace command, probably the most often-used command of sed.

The search expression:

^ = from the beginning of a line...

\(.\) = ...take a single character and remember it...

[^_]*_ = ...which is followed by any number of non-underscore characters, followed by a single underscore.

\(.*\)$ = After the underscore, take everything and remember it too.

The replacement expression:

\1_\2 = The first thing we asked sed to remember, followed by an underscore and the second thing.

MK
MK
Marco A.
Esteemed Contributor

Re: Need to grep for first initial and lastname

I needed to do something similar, and this reg expression works for me too, thanks!

Marco,
Just unplug and plug in again ....
James R. Ferguson
Acclaimed Contributor

Re: Need to grep for first initial and lastname

Hi Allan:

# X="firstname_lastname"
# echo ${X}|perl -ple 's/^(.)(?:.+?)(_.+)/$1$2/'

f_lastname

Regards!

...JRF...
Suraj K Sankari
Honored Contributor

Re: Need to grep for first initial and lastname

Hi,

You can do it like this way also
awk 'BEGIN { FS = "_" } ; { print substr($0,1,1)"_"$2 }' output file

Suraj