tags:

views:

81

answers:

3

Hello, I need to print last 20 characters of string, but only whole words. Delimiter is a space "". Let's 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 it to return over the lazy dog instead. Do you know how to accomplish that? Thanks!

+3  A: 
echo $string | perl -ne 'print "$1\n" if /\b(\S.{0,20})$/'
Marcelo Cantos
Very nice, thank you.
Andrew
Using grep: echo $string | egrep -o '\<.{0,20}$'
UdiM
@UdiM: You should make that an answer.
Dennis Williamson
+2  A: 
echo $string | rev | cut -d ' ' -f -20
NixNinja
That outputs the *first* twenty *words*.
Dennis Williamson
lol... well spotted, changed it with rev, but it still wont work over muptiple lines... will research...
NixNinja
+1  A: 

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.

Dennis Williamson