# String Truncation in Shell Script

Any time you have to truncate a string in shell scripting environment? Don’t be panic or even turn to Python. Here are roughly eight ways of string truncation in shell scripting.

• % truncation: delete the sub-string in the right side, but retain the sub-string in the left side.

%.* means starting from the right side, delete all characters until the first . is met. Note that the first . is also deleted. The final result is: Hand_bag-114_cluth_0

• # truncation: delete the substring in the left side, but retain the sub-string in the right side.

#*_ means staring from the right side, delete all characters until the first _ is met. Similarly, the first _ would also be delted. The final rsult is: bag-114_cluth_0.jpg

• ## and %% truncation: unlike the two aforementioned commands, the two comannds scan until the last (yes, not the first) pattern is met.
• :n1:n2 truncation: starting from the left side with the location n1, keep n2 characters and delete all others.
• :n1 truncation: starting from the left side with the location n1, keep all characters until the string ends. Note the character of location n1 would be kept.
• :0-n1:n2 truncation: what if we need to keep characters from the right side. This is a simple trick to do this: just adding 0- to the start point. Note that, since counting from the right side, we start from 1. After find the start point, we continue to keep characters from left-to-right
• :0-n1 truncation: similar to the previous one. But as n2 is omitted, we keep all characters until the string ends.

One more thing: how to assign the truncated string to a new variable. Here is it: var2=\backquote echo {var:0-10}\backquote