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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10218474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:57:34  来源:igfitidea点击:

How to obtain the first letter in a Bash variable?

bashtext-processingvariable-expansion

提问by Village

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

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

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:

如何创建一个新的 Bash 变量,它仅等于变量中找到的第一个字母?例如,以上将是:

echo $firstletter
t

Or:

或者:

echo $firstletter
T

采纳答案by thiton

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

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

每次您在问题描述中说“第一”时,head都是可能的解决方案。

回答by Karoly Horvath

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

回答by Adam Liss

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

回答by Mateusz Piotrowski

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

一种可移植的方法是使用参数扩展(这是 POSIX 功能)

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

回答by Franckyz

With cut :

带切:

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

回答by phicr

Since you have a sedtag here is a sedanswer:

既然你有一个sed标签,这里是一个sed答案:

echo "$word" | sed -e "{ s/^\(.\).*// ; 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 sedso it won't repeat this block for other lines if there are any.
  • s: 开始替换例程
    • /: 开始指定要替换的内容
    • ^\(.\): 捕获第 1 组中的第一个字符
    • .*:, 确保该行的其余部分将在替换中
    • /: 开始指定替换
    • \1: 插入组 1
    • /: 剩下的丢了;
  • q: 退出,sed这样它就不会在其他行重复这个块(如果有的话)。

}

}

Well that was fun! :)You can also use grepand etc but if you're in bashthe ${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 :()

那很有趣!:)您也可以使用grep和等,但如果你是bash${x:0:1}magick仍是更好的解决方案海事组织。(我花了大约一个小时试图使用 POSIX 变量扩展来做到这一点,但不能:(

回答by leogtzr

Using bash 4:

使用 bash 4:

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