2012-01-05

Trimming suffix or perfix of a string in Shell

by Forrest Sheng Bao http://fsbao.net

How to trim/truncate a string in Linux? Especially when it is a path or file name?

See this demo below.

test="~/bin/test_label"

echo ${test%_label} # the percentage sign means from the end

echo ${test#?/*/} # the pound sign means from the start 

Save it as a Shell script (e.g., test.sh) and test it on your Shell:

$ sh test.sh 
~/bin/test
test_label

Got the idea?

This is very simple string matching, where question mark and asterisk have their normal meanings in UNIX regular expression.

No comments: