Stripping Variable Strings By length:
Syntax: ${parameter:starting_index:number_of_chars}
${variable:3} # foobar becomes bar ${variable:3:2} # foobar becomes ba ${variable: -4} # foobar becomes obar
Upper and lower case :
y="this IS small" echo "${y^^}" THIS IS SMALL y="THIS is BIG" echo "${y,,}" this is big
Removing a Part:
This will remove 'removepatt' from variable(begining) var and assign to name
name=${var%removepat}
can use % to remove the pattern at the end. useful when one wish to remove trailing / from path names
## Deletes longest match of $removepat from front of $var.
%% Deletes longest match of $removepat from back of $var.
Here is the example which will tokenize positional parameters based on =
tmp=${1} parameter=${tmp%%=*} # Extract name. value=${tmp##*=} # Extract value.
if $1 is a=1, then
parameter=a #strip from back till = ; so =* will be removed
value=1 # strip from front till = ; so *= will be removed
Substring Replacement:
${string/substring/replacement}
Following will simply delete the pattern from string.
string=abcABC123ABCabc echo ${string/abc/xyz} # xyzABC123ABCabc echo ${string//abc/xyz} # xyzABC123ABCxyz
string=abcABC123ABCabc echo ${string/abc/} # ABC123ABCabc echo ${string//abc/} # ABC123ABC
Get Length:
To calculate length of any variable in shell, # can be used.
a="ABCD" ${#a} 4
Calculate number of elements in array:
$ os=("linux" "solaris" "aix") $ echo {#os[*]} 3 $ echo {#os[@]} 3
@ or * can be used to access all elaments of an array.
These native methods will be faster since we are not invoking any third party tools.
Note: without '( )' result can't be treated as array.
AWK/CUT implementation (simplified) :
dinesh@ubuntu:~$ a="abc 123 qqq" dinesh@ubuntu:~$ set -- $a dinesh@ubuntu:~$ echo $1 abc dinesh@ubuntu:~$ echo $2 123 dinesh@ubuntu:~$ echo $3 qqq dinesh@ubuntu:~$
0 comments:
Post a Comment