[nSLUG] Extracting first char from shell var

Dop Ganger nslug at fop.ns.ca
Thu Feb 13 15:03:43 AST 2014


It's matching up to one character. Try:

for i in `seq 1 100` ; do echo testuser | grep -Eo '[a-z]{'${i}'}' ; done

vs

for i in `seq 1 100` ; do echo testuser | grep -Eo '^[a-z]{'$i'}' ; done

vs

for i in `seq 1 100` ; do echo testuser | grep -Eo '[a-z]{'$i'}$' ; done

Does that help explain what's going on? I picked 100 as an arbitrarily 
large number that wasn't too large.

Cheers... Dop.

On Thu, 13 Feb 2014, D G Teed wrote:

> 
> Say I've got a username in a shell variable
> mailuser with the value "testuser".  I want to extract
> the first letter in the user name because it
> is needed to walk the cyrus mail directory tree.
> 
> So one answer is:
> 
> echo ${mailuser:0:1}
> t
> 
> Now that we've got that out of the way, I'm curious
> what is happening in this:
> 
> echo $mailuser | grep -Eo '[a-z]{1}'
> t
> e
> s
> t
> u
> s
> e
> r
> 
> Same without the pipe:
> 
> cat /tmp/testfile
> testuser
> 
> grep -Eo '[a-z]{1}' /tmp/testfile
> t
> e
> s
> t
> u
> s
> e
> r
> 
> 
> Whereas I've used patterns in -Eo to extract IP addresses,
> and this works as expected:
> 
> grep -Eo ' [a-z]{9}$' /etc/hosts
>  localhost
> 
> 
> 
>


More information about the nSLUG mailing list