如何获得 Bash 变量中的第一个字母?

我有一个 Bash 变量 $word,它有时是一个单词或句子,例如:

word="tiger"

或者:

word="This is a sentence."

如何创建一个新的 Bash 变量,它只等于在变量中找到的第一个字母?例如:

echo $firstletter
t

或者:

echo $firstletter
T
95585 次浏览
initial="$(echo $word | head -c 1)"

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

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

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 :( )

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

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

Using bash 4:

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

With cut :

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