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

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

string最后三个字符:

 ${string: -3} 

要么

 ${string:(-3)} 

(介意第一种forms的-3-3之间的空格)。

请参考参考手册中的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. 

既然这个答案得到了一些定期的意见,让我来增加一个可能性来解决约翰·里克斯的评论; 正如他所提到的,如果你的string长度小于3, ${string: -3}将展开为空string。 如果在这种情况下,你想扩展string ,你可以使用:

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

这使用?:三元if运算符,可以在Shellalgorithm中使用 ; 自logging以来,偏移量是一个算术expression式,这是有效的。

你可以使用tail

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

得到最后三个字符有点迂回的方法是说:

 echo $foo | rev | cut -c1-3 | rev 

另一个解决方法是使用grep -o用一点正则expression式来得到三个字符,然后是行尾:

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

为了使它可以得到1到3个最后的字符,如果stringless于3个字符,可以使用egrep和这个正则expression式:

 $ 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来得到最后的五到十个字符。

为了概括gniourf_gniourf的问题和答案(因为这是我正在search的内容),如果要从一开始的第7个字符到最后的第3个字符,可以使用以下语法:

 ${string: -7:4} 

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

另外,虽然gniourf_gniourf的解决scheme显然是最好的和最好的,我只是想添加一个替代解决scheme:

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

如果通过将$ {#string}长度定义为一个单独的variables,将它分成两行,这样更具可读性。