How to get the first letter in a Bash variable?

I have a Bash variable, $word , which is sometimes a word or sentence, for example:

 word="tiger" 

Or:

 word="This is a sentence." 

How can I create a new Bash variable that is equal only to the first letter found in the variable? For example, the above would be:

 echo $firstletter t 

Or:

 echo $firstletter t 
+72
bash text-processing variable-expansion
Apr 18 2018-12-18T00:
source share
7 answers
 initial="$(echo $word | head -c 1)" 

Each time you say β€œfirst” in the description of the problem, head is the likely solution.

+23
Apr 18 '12 at 21:44
source share
 word="tiger" firstletter=${word:0:1} 
+223
Apr 18 2018-12-18T00:
source share
 word=something first=${word::1} 
+66
Apr 18 2018-12-18T00:
source share

A portable way to do this is to use a parameter extension (which is a POSIX function) :

 $ word='tiger' $ echo "${word%"${word#?}"}" t 
+10
Jul 08 '17 at 16:45
source share

Since you have a sed tag, here is the sed answer:

 echo "$word" | sed -e "{ s/^\(.\).*/\1/ ; q }" 

Play the game for those who like it (I do!):

{

  • s : run lookup
    • / : Start by indicating what needs to be replaced.
    • ^\(.\) : capture the first character in group 1
    • .* :, make sure the rest of the line is in the wildcard
    • / : start specifying a replacement
    • \1 : insert group 1
    • / : The rest is discarded ;
  • q : Close sed so that it does not repeat this block for other lines, if any.

}

Ok, that was fun! :) You can also use grep , etc., but if you are in bash , the magic of ${x:0:1} is still imo's best solution. (I spent an hour trying to use the POSIX variable extension, but could not :( )

+2
Mar 01 '17 at 18:00
source share

With a neckline:

 word='tiger' echo "${word}" | cut -c 1 
+2
Aug 30 '18 at 2:59
source share

Using bash 4:

 x="test" read -N 1 var <<< "${x}" echo "${var}" 
+1
Oct 22 '17 at 5:40 on
source share



All Articles