如何在bash中提取子字符串

MOH*_*MED 17 linux bash shell

我在bash中有以下字符串,长度> 4

str = "abcdefghijklmno"
Run Code Online (Sandbox Code Playgroud)

我想提取到str25的第一个字符str.所以

str2="abcde"
Run Code Online (Sandbox Code Playgroud)

如何用bash做到这一点?

fed*_*qui 37

请使用表达式

{string:position:length}
Run Code Online (Sandbox Code Playgroud)

所以在这种情况下:

$ str="abcdefghijklm"
$ echo "${str:0:5}"
abcde
Run Code Online (Sandbox Code Playgroud)

查看其他用法:

$ 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
Run Code Online (Sandbox Code Playgroud)

摘自:
- wooledge.org - 如何使用参数扩展?我如何获得子串?如何在没有扩展名的情况下获取文件,或只获取文件的扩展名?
- Shell命令语言 - 2.6.2参数扩展

  • 这是正确的答案,但我建议使用不同的参考 - 由freenode的#bash认为ABS被认为是错误的来源,而不是智慧.考虑一下http://mywiki.wooledge.org/BashFAQ/073 (2认同)