How to obtain the first letter in a Bash variable?

眉间皱痕 提交于 2020-01-28 04:22:07

问题


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

回答1:


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

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




回答2:


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



回答3:


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



回答4:


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

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



回答5:


With cut :

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



回答6:


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




回答7:


Using bash 4:

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


来源:https://stackoverflow.com/questions/10218474/how-to-obtain-the-first-letter-in-a-bash-variable

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