Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I truncate a line of text longer than a given length?

How would you go about removing everything after x number of characters? For example, cut everything after 15 characters and add ... to it.

This is an example sentence should turn into This is an exam...

like image 837
undefinedChar Avatar asked Sep 01 '25 01:09

undefinedChar


2 Answers

GnuTools head can use chars rather than lines:

head -c 15 <<<'This is an example sentence'

Although consider that head -c only deals with bytes, so this is incompatible with multi-bytes characters like UTF-8 umlaut ü.

Bash built-in string indexing works:

str='This is an example sentence'
echo "${str:0:15}"

Output:

This is an exam

And finally something that works with ksh, dash, zsh…:

printf '%.15s\n' 'This is an example sentence'

Even programmatically:

n=15
printf '%.*s\n' $n 'This is an example sentence'

If you are using Bash, you can directly assign the output of printf to a variable and save a sub-shell call with:

trim_length=15
full_string='This is an example sentence'
printf -v trimmed_string '%.*s' $trim_length "$full_string"
like image 132
Léa Gris Avatar answered Sep 02 '25 16:09

Léa Gris


Use cut:

echo "This is an example sentence" | cut -c1-15
This is an exam

This includes characters (to handle multi-byte chars) 1-15, c.f. cut(1)

     -b, --bytes=LIST
            select only these bytes

     -c, --characters=LIST
            select only these characters
like image 22
LeadingEdger Avatar answered Sep 02 '25 16:09

LeadingEdger