我在bash中有以下字符串,长度为> 4
str = "abcdefghijklmno"
我想要提取str2
str
的第一个字符str2="abcde"
。所以
{{1}}
如何用bash做到这一点?
答案 0 :(得分:35)
请使用表达式
{string:position:length}
所以在这种情况下:
$ str="abcdefghijklm"
$ echo "${str:0:5}"
abcde
见其他用法:
$ echo "${str:0}" # default: start from the 0th position
abcdefghijklm
$ echo "${str:1:5}" # start from the 1th and get 5 characters
bcdef
$ echo "${str:10:1}" # start from 10th just one character
k
$ echo "${str:5}" # start from 5th until the end
fghijklm
取自:
- wooledge.org - How can I use parameter expansion? How can I get substrings? How can I get a file without its extension, or get just a file's extension?
- Shell Command Language - 2.6.2 Parameter Expansion