How to obtain the first letter in a Bash variable?

我是研究僧i 提交于 2019-12-02 21:32:35
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}

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

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

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

With cut :

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

Using bash 4:

x="test"
read -N 1 var <<< "${x}"
echo "${var}"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!