庆典:访问字符串的最后x个字符 [英] bash: Accessing last x characters of string

查看:121
本文介绍了庆典:访问字符串的最后x个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现,与 $ {字符串:0:3} 可以访问一个字符串的前3个字符。是否有一个等价简单的方法来访问例如最后三个字符?

I found out that with ${string:0:3} one can access the first 3 characters of a string. Is there a equivalently easy method to access e.g. the last three characters?

推荐答案

字符串的最后三个字符:

${string: -3}

${string:(-3)}

(介意之间的空间 -3 中的第一种形式)。

请参阅壳牌参数扩展参考手册

${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.


由于这个答案得到了一些常规的看法,让我补充一个可能解决的约翰·里克斯评论;他提到,如果你的字符串具有小于3的长度, $ {字符串:-3} 扩展为空字符串。如果在这种情况下,你希望字符串的扩展,你可以使用:


Since this answer gets a few regular views, let me add a possibility to address John Rix's comment; as he mentions, if your string has length less than 3, ${string: -3} expands to the empty string. If, in this case, you want the expansion of string, you may use:

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

本使用三元如果运营商,可以在的Shell算术的;因为作为记录,偏移量是一个算术前pression,这是有效的。

This uses the ?: ternary if operator, that may be used in Shell Arithmetic; since as documented, the offset is an arithmetic expression, this is valid.

这篇关于庆典:访问字符串的最后x个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆