Wednesday, November 17, 2010

Unix substring

${#string} - Length of String
${string:position} - extract substring from $string at $position
-- position argument starts at 0, not 1.
${string/substring/replacement} - replace first match of $substring with $replacement
${string//substring/replacement} - replace all matches of $substring with $replacement
${string/#substring/replacement} - If $substring matches front end of $string, substitute $replacement for $substring
${string/%substring/replacement} - If $substring matches back end of $string, substitute $replacement for $substring
${string#substring} - Strip shortest match of $substring from front of $string
${string##substring} - Strip longest match of $substring from front of $string
${string%substring} - Strip shortest match of $substring from back of $string
${string%%substring} - Strip longest match of $substring from back of string

EXAMPLES
file=jack_of_all_trades
echo ${#file}
18

echo ${file:12}
trades

echo ${file:5:2}
of

echo ${file/of/OF}
jack_OF_all_trades

echo ${file//a/A}
jAck_of_All_trAdes

echo ${file:0:4}
jack

echo ${file/#j/A}
Aack_of_all_trades

echo ${file/%s/A}
jack_of_all_tradeA

file=aaa_bbb_ccc_aaa
echo ${file#aaa}
_bbb_ccc_aaa

echo ${file%aaa}
aaa_bbb_ccc_


No comments:

Post a Comment