I am looking for a way to extract substrings to local variables. Here is the format of the string variable i am using :
/var/x/www && /usr/x/share/doc && /etc/x/logs
where the substrings i must extract are the "/var/x/www" and such.
I was originally thinking of using something like "awk" to extract each substring and place them in $1, $2.....$NF which would be perfect.
Does anyone have an idea?
Do you have control over the field separator character? If you used a more common separator like a pipe (or converted " && " to a pipe before processing it) you could parse the string and put the values into an array (I am using ksh93 on Solaris by the way):
#!/usr/dt/bin/dtksh
# Set a string variable.
pathlist="/var/x/www|/usr/x/share/doc|/etc/x/logs"
# Set the Input Field Separator.
IFS='|'
# Create an array, with elements automatically parsed by the IFS string.
set -A parsed_pathlist_array $pathlist
# Prove it works.
print "1: ${parsed_pathlist_array[0]}"
print "2: ${parsed_pathlist_array[1]}"
print "3: ${parsed_pathlist_array[2]}"
exit 0
However the interesting part of "awk" is that the number of strings in the variable changes from line to line, thus the $NF token in awk is really useful there
---------- Post updated at 06:21 PM ---------- Previous update was at 04:35 PM ----------
My example works with ksh93 on solaris. You will have to do some searching to see if you can do the equivalent on your system and shell.
P.S. For looping, the syntax to get the number of entries in the array is:
${#arrayname
[*]}
which would allow for dynamically looping through the array. Modified example:
#!/usr/dt/bin/dtksh
# Set a string variable.
pathlist="/var/x/www|/usr/x/share/doc|/etc/x/logs"
integer ctr=0
integer nbr_elements
# Set the Input Field Separator.
IFS='|'
# Create an array, with elements automatically parsed by the IFS string.
set -A parsed_pathlist_array $pathlist
nbr_elements=${#parsed_pathlist_array
[*]}
# Prove it works. Loop through the array.
while (( $ctr < $nbr_elements ))
do
print "array element $ctr: ${parsed_pathlist_array[$ctr]}"
((ctr+=1))
done
exit 0
I'm not a bash guy, but I played around for the fun of it and this works to parse a string:
#!/bin/bash
# Set a string variable.
pathlist="/var/x/www|/usr/x/share/doc|/etc/x/logs"
ctr=0
# Set the Input Field Separator.
IFS='|'
# Prove it works. Loop
for element in $pathlist
do
echo "substring element $ctr: $element"
ctr=`expr $ctr + 1`
done
exit 0