【问题标题】:how to extract a substring in bash如何在bash中提取子字符串
【发布时间】:2013-05-10 14:46:54
【问题描述】:

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

str = "abcdefghijklmno"

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

str2="abcde"

如何用 bash 做到这一点?

【问题讨论】:

  • 您可以通过man bash 来查看此类内容的命令列表

标签: linux bash shell


【解决方案1】:

请使用表达式

{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

【讨论】:

  • +1 表示不使用“外部”命令。 :) 最好将结果放入str2,如 OP 所愿。
  • 这是正确的答案,但我建议使用不同的参考——freenode 的#bash 认为 ABS 是错误的来源,而不是智慧的来源。考虑mywiki.wooledge.org/BashFAQ/073
  • 当我尝试这个时,我得到了错误的答案 arg=$1 echo "arg is $arg" nm="${arg:0,5}" echo "name is: $nm" arg is abcdefghijklmnop 名称是:fghijklmnop
  • @slashdottir 注意你使用的是${arg:0,5}(注意逗号),而我使用的是${arg:0:5}(冒号)。
  • 要删除最后 4 个字符,echo ${f:0:-4}
猜你喜欢
  • 2021-10-31
  • 2014-05-15
  • 2015-04-26
  • 2023-03-17
  • 2012-09-24
  • 2019-06-22
相关资源
最近更新 更多