Linux tail only whole words

I need to print the last 20 characters of a string, but only whole words. The separator is a space "

". Consider this example:

string = "The quick brown fox jumps over the lazy dog"
  echo $ string | tail -c20

returns s over the lazy dog

. And I need him to return over the lazy dog

. Do you know how to do it? Thank!

+2


source to share


3 answers


echo $string | perl -ne 'print "$1\n" if /\b(\S.{0,20})$/'

      



+3


source


echo $string | rev | cut -d ' ' -f -20

      



+2


source


This works in Bash> 3.2 without using any external programs:

[[ $string =~ \ (.{0,20})$ ]]
result="$BASH_REMATCH[1]"

      

I used the UdiM version as a basis grep

.

+1


source







All Articles