Some birds are not meant to be caged, their feathers are just too bright.

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.

12

var=Hand_bag-114_cluth_0.jpg
echo${var%.*}

%.* 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.

12

var=Hand_bag-114_cluth_0.jpg
echo${var#*_}

#*_ 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.

123

var=Hand_bag-114_cluth_0.jpg
echo${var%%_*}#Handecho${var##*_}#0.jpg

:n1:n2 truncation: starting from the left side with the location n1, keep n2 characters and delete all others.

12

var=www.google.com
echo${var:0:3}#www

: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.

12

var=www.google.com
echo${var:4}#google.com

: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

12

var=www.google.com
echo${var:0-10:6}#google

:0-n1 truncation: similar to the previous one. But as n2 is omitted, we keep all characters until the string ends.

12

var=www.google.com
echo${var:0-10}#google.com

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