[nSLUG] Extracting first char from shell var

Douglas Guptill dguptill at accesswave.ca
Thu Feb 13 15:34:48 AST 2014


On Thu, Feb 13, 2014 at 02:51:07PM -0400, 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

Only if your shell is 'bash'.  Fails in 'dash'.


> 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

For more fun, try changing the '1'

  $ mailuser=testuser
  $ echo $mailuser | grep -Eo '[a-z]{2}'
  te
  st
  us
  er

  $ echo $mailuser | grep -Eo '[a-z]{3}'
  tes
  tus

An alternative is to use 'cut'

  $ echo ${mailuser} | cut -c1
  t

  $ echo ${mailuser} | cut -c2
  e

  $ echo ${mailuser} | cut -c1,1
  t

  $ echo ${mailuser} | cut -c1,2
  te

Douglas.
-- 
Bold character derived from stubborn patience and adversity.


More information about the nSLUG mailing list