consider this is a line A#B#C#D#E#F#G#H
note the delimeter is #
i want to cut or spilt in to fields using the delimeter # and to store in an array.
like this
array[0]=A
array[1]=B
array[2]=C
array[3]=D
array[4]=E
and the array content should be displayed.
echo "${array[$0]}"
echo "${array[$1]}"
echo "${array[$2]}"
echo "${array[$3]}"
echo "${array[$4]}"
provide me code and i am using bash script.
Thanks
barani
kshji
February 23, 2010, 1:32am
2
Same answer as two days ago .
This work with all posix-sh compatible shells (ksh, posixsh, bash, ...).
oifs="$IFS" # -save IFS value
IFS="#"
flds=( $fileline )
IFS="oifs" # - return original alue
nrofflds=${#flds[@]}
fld1="${flds[0]}"
fld=0
while (( fld<nrofflds ))
do
echo "{flds[$fld]}"
((fld+=1))
done
devtakh
February 23, 2010, 1:36am
3
In perl:
$str="A#B#C#D#E#F#G#H";
@arr=split(/#/,$str);
for($i=0;$i<=$#arr;$i++)
{
print "Array at pos $i is:$arr[$i]\n";
}
cheers,
Devaraj Takhellambam
You can use the cut command with the -d option. this is used to specify the delimiter
And you can specify the field numbers using -f.
echo A#B#C#D#E#F#G#H | "cut -d"#" -f 1
The above code will give 'A'. Then assign this to array[$0]
obviously A#B#C#D#E#F#G#H | "cut -d"#" -f 2 will give 'B'
and so on
For specifying the index you used $0,$1,etc.I thing you misunderstood wrongly .just use 0,1,etc for the index.
Here is the solution.using the IFS you can achieve it easily.
str="A#B#C#D#E#F#G#H"
IFS="#"
array=( $str )
echo "${array[0]}"
echo "${array[1]}"
echo "${array[2]}"
echo "${array[3]}"
echo "${array[4]}"
Karthi's is simple and straight forward but as a code discipline we should follow some rules like we must not change the IFS variable.
for that we must keep the IFS value by take a copy of that
hence I change his code with a little difference
str="A#B#C#D#E#F#G#H"
tmp=$IFS ; # take a copy
IFS="#"
array=( $str )
echo "${array[0]}"
echo "${array[1]}"
echo "${array[2]}"
echo "${array[3]}"
echo "${array[4]}"
IFS =$tmp; # get back the previous value