How to obtain the first letter in a Bash variable?

后端 未结 7 1004
無奈伤痛
無奈伤痛 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:40

    With cut :

    word='tiger'
    echo "${word}" | cut -c 1
    
    0 讨论(0)
  • 2020-12-14 05:45

    Using bash 4:

    x="test"
    read -N 1 var <<< "${x}"
    echo "${var}"
    
    0 讨论(0)
  • 2020-12-14 05:46
    initial="$(echo $word | head -c 1)"
    

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

    0 讨论(0)
  • 2020-12-14 05:48
    word=something
    first=${word::1}
    
    0 讨论(0)
  • 2020-12-14 05:49

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

    $ word='tiger'
    $ echo "${word%"${word#?}"}"
    t
    
    0 讨论(0)
  • 2020-12-14 05:56
    word="tiger"
    firstletter=${word:0:1}
    
    0 讨论(0)
提交回复
热议问题