How to obtain the first letter in a Bash variable?

后端 未结 7 1003
無奈伤痛
無奈伤痛 2020-12-14 05:27

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

word=\"tiger\"

Or:

word=\"This is          


        
7条回答
  •  一生所求
    2020-12-14 05:57

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

提交回复
热议问题