I need to print last 20 characters of string, but only whole words. Delimiter is a space "". Let's consider this exampl开发者_开发技巧e:
string="The quick brown fox jumps over the lazy dog"
echo $string | tail -c20
returns s over the lazy dog
. And I need it to return over the lazy dog
instead. Do you know how to accomplish that? Thanks!
echo $string | perl -ne 'print "$1\n" if /\b(\S.{0,20})$/'
echo $string | rev | cut -d ' ' -f -20
This works in Bash > 3.2 without using any external programs:
[[ $string =~ \ (.{0,20})$ ]]
result="$BASH_REMATCH[1]"
I used UdiM's grep
version as a basis.
精彩评论