开发者

Linux tail only whole words

开发者 https://www.devze.com 2022-12-26 02:34 出处:网络
I need to print last 20 characters of string, but only whole words. Delimiter is a space \"\". Let\'s consider this exampl开发者_开发技巧e:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消