加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在Bash中访问字符串的最后x个字符

发布时间:2020-12-15 18:59:58 所属栏目:安全 来源:网络整理
导读:我发现使用${string:0:3}可以访问字符串的前3个字符.是否有一个等效的方法来访问最后三个字符? 字符串的最后三个字符: ${string: -3} 要么 ${string:(-3)} (注意第一种形式中的:和-3之间的空间). 请参考Shell Parameter Expansion in the reference man
我发现使用${string:0:3}可以访问字符串的前3个字符.是否有一个等效的方法来访问最后三个字符?
字符串的最后三个字符:
${string: -3}

要么

${string:(-3)}

(注意第一种形式中的:和-3之间的空间).

请参考Shell Parameter Expansion in the reference manual:

${parameter:offset}
${parameter:offset:length}

Expands to up to length characters of parameter starting at the character
specified by offset. If length is omitted,expands to the substring of parameter
starting at the character specified by offset. length and offset are arithmetic
expressions (see Shell Arithmetic). This is referred to as Substring Expansion.

If offset evaluates to a number less than zero,the value is used as an offset
from the end of the value of parameter. If length evaluates to a number less than
zero,and parameter is not ‘@’ and not an indexed or associative array,it is
interpreted as an offset from the end of the value of parameter rather than a
number of characters,and the expansion is the characters between the two
offsets. If parameter is ‘@’,the result is length positional parameters
beginning at offset. If parameter is an indexed array name subscripted by ‘@’ or
‘*’,the result is the length members of the array beginning with
${parameter[offset]}. A negative offset is taken relative to one greater than the
maximum index of the specified array. Substring expansion applied to an
associative array produces undefined results.

Note that a negative offset must be separated from the colon by at least one
space to avoid being confused with the ‘:-’ expansion. Substring indexing is
zero-based unless the positional parameters are used,in which case the indexing
starts at 1 by default. If offset is 0,and the positional parameters are used,$@ is prefixed to the list.

由于这个答案得到了一些常规观点,让我添加一个解决John Rix评论的可能性;正如他所提到的,如果你的字符串长度小于3,${string:-3}会扩展为空字符串.在这种情况下,如果要扩展字符串,可以使用:

${string:${#string}<3?0:-3}

这使用了可以在Shell Arithmetic中使用的?:ternary if运算符;因为有记载,偏移是一个算术表达式,这是有效的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读