Tuesday, October 4, 2011

substring in unix shell scripts

Recently I need to handle quite some unix shell scripts and find some tricks about strings that is less known.

1. substring
Most of my searches resulted using awk. I don't mind using it, but it make the script less readable. Luckily there is a easy way:
one_str="this is a string"
sub_str=${one_str:5:2} # ${org_str_var:0_based_index:length}
# now sub_str contains "is"
2. string search and replacement
Again, most search results say you should use "sed" or other external commands. But below line will also do the trick:
alpha="This is a test string in which the word \"test\" is replaced." beta="${alpha/test/replace}" #replace only the 1st insance
beta="${alpha//test/replace}" #replace all insances