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

我发现用${string:0:3}可以访问字符串的前3个字符。 是否有一个等效的方法来访问最后三个字符?

aldorado asked 2019-08-12T03:45:46Z
4个解决方案
177 votes

最后三个字符?:

${string: -3}

要么

${string:(-3)}

(请注意第一种形式的?:string之间的空格)。

请参考参考手册中的Shell参数扩展:

${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,则可以使用:

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

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

gniourf_gniourf answered 2019-08-12T03:46:29Z
38 votes

你可以使用tail

$ foo="1234567890"
$ echo -n $foo | tail -c 3
890

获得最后三个字符的有点迂回方式是:

echo $foo | rev | cut -c1-3 | rev
devnull answered 2019-08-12T03:47:01Z
8 votes

另一个解决方法是使用带有一点regex魔法的5,10获得三个字符,然后是行尾:

$ foo=1234567890
$ echo $foo | grep -o ...$
890

为了使它可选地获得1到3个最后一个字符,如果字符串少于3个字符,你可以使用5,10这个正则表达式:

$ echo a | egrep -o '.{1,3}$'
a
$ echo ab | egrep -o '.{1,3}$'
ab
$ echo abc | egrep -o '.{1,3}$'
abc
$ echo abcd | egrep -o '.{1,3}$'
bcd

您还可以使用不同的范围,例如5,10来获取最后五到十个字符。

Aurelio Jargas answered 2019-08-12T03:47:40Z
4 votes

为了概括gniourf_gniourf的问题和答案(因为这是我正在搜索的内容),如果你想从最后的第7个到最后的第3个剪切一系列字符,你可以使用这个语法:

${string: -7:4}

其中4是课程长度(7-3)。

另外,虽然gniourf_gniourf的解决方案显然是最好的和最好的,但我只想添加一个使用cut的替代解决方案:

echo $string | cut -c $((${#string}-2))-$((${#string}))

如果通过将长度$ {#string}定义为单独的变量,可以在两行中执行此操作,则更具可读性。

Adrian Tompkins answered 2019-08-12T03:48:27Z
translate from https://stackoverflow.com:/questions/19858600/accessing-last-x-characters-of-a-string-in-bash