linux - 如何在bash中提取子字符串

标签 linux bash shell

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

str = "abcdefghijklmno"

我想将 str 的第 5 个字符提取到 str2 中。所以

str2="abcde"

如何用 bash 做到这一点?

最佳答案

请使用表达式

{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

关于linux - 如何在bash中提取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16484972/

相关文章:

linux - 'cat foo.txt | my_cmd' 和 'my_cmd < foo.txt' 完成同样的事情吗?

linux - 在 bash 中读取 [命令]

python - 如何在 Python 中正确地将双引号传递给 awk 子进程?

linux - bash 中前面注释的第一个参数的简写是什么?最后是 '$!'

c++ - 我如何在 linux 中获取程序的版本

linux - mlock() 如何与休眠一起工作?

linux - BASH:可以在命令行上进行 grep,但不能在脚本中进行

bash - 如何在 linux [bash shell] 中传递 ' [单引号字符] 作为参数?

linux - 从 Windows 到 Linux 交叉编译 dotnet 核心应用程序