How to obtain the first letter in a Bash variable?

BashText ProcessingVariable Expansion

Bash Problem Overview


I have a Bash variable, $word, which is sometimes a word or sentence, e.g.:

word="tiger"

Or:

word="This is a sentence."

How can I make a new Bash variable which is equal to only the first letter found in the variable? E.g., the above would be:

echo $firstletter
t

Or:

echo $firstletter
T

Bash Solutions


Solution 1 - Bash

word="tiger"
firstletter=${word:0:1}

Solution 2 - Bash

word=something
first=${word::1}

Solution 3 - Bash

initial="$(echo $word | head -c 1)"

Every time you say "first" in your problem description, head is a likely solution.

Solution 4 - Bash

A portable way to do it is to use parameter expansion (which is a POSIX feature):

$ word='tiger'
$ echo "${word%"${word#?}"}"
t

Solution 5 - Bash

With cut :

word='tiger'
echo "${word}" | cut -c 1

Solution 6 - Bash

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

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

Play by play for those who enjoy those (I do!):

{

  • s: start a substitution routine
    • /: Start specifying what is to be substituted
    • ^\(.\): capture the first character in Group 1
    • .*:, make sure the rest of the line will be in the substitution
    • /: start specifying the replacement
    • \1: insert Group 1
    • /: The rest is discarded;
  • q: Quit sed so it won't repeat this block for other lines if there are any.

}

Well that was fun! :) You can also use grep and etc but if you're in bash the ${x:0:1} magick is still the better solution imo. (I spent like an hour trying to use POSIX variable expansion to do that but couldn't :( )

Solution 7 - Bash

Using bash 4:

x="test"
read -N 1 var <<< "${x}"
echo "${var}"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVillageView Question on Stackoverflow
Solution 1 - BashKaroly HorvathView Answer on Stackoverflow
Solution 2 - BashAdam LissView Answer on Stackoverflow
Solution 3 - BashthitonView Answer on Stackoverflow
Solution 4 - BashMateusz PiotrowskiView Answer on Stackoverflow
Solution 5 - BashFranckyzView Answer on Stackoverflow
Solution 6 - BashphicrView Answer on Stackoverflow
Solution 7 - BashleogtzrView Answer on Stackoverflow