[NTLUG:Discuss] Strings in BASH, an easier way?

David Stanaway david at stanaway.net
Wed Dec 24 01:13:02 CST 2008


david at sprocket:~$ set IFS=:
david at sprocket:~$ declare -a FOO
david at sprocket:~$ for p in $PATH; do FOO=("${FOO[@]}" "$p"); done
david at sprocket:~$ echo ${#FOO[@]}
5
david at sprocket:~$ echo ${FOO[0]}
/usr/local/bin
david at sprocket:~$ echo ${FOO[1]}
/usr/bin
david at sprocket:~$ echo ${FOO[2]}
/bin
david at sprocket:~$ echo ${FOO[3]}
/usr/bin/X11
david at sprocket:~$ echo ${FOO[4]}
/usr/games

You don't need to use an array there. You could do whatever you want to 
do in the loop instead of the array push.  I though PATH was a special 
bash array but I was mis-remembering.

David Stanaway wrote:
> Bash handles ARRAY types. That is how it handles PATH.
>
> Look for ARRAY in man bash
>
> Leroy Tennison wrote:
>   
>> I'm wanting to split a string in BASH.  I know about gawk and maybe sed 
>> but I'm looking for a less involved solution.  The simplest I've found 
>> so far is the cut program but I'm wondering if there is something even 
>> simpler.
>>
>> To add some context, what surfaced this is I wanted to do an apropos on 
>> all programs in my path.  What I have at this point is:
>>
>> for i in `echo $PATH | cut -d: -f1-30 --output-delimiter=" "`; do
>> for j in `ls -1 $i`; do apropos $j; read; done;
>> done
>>
>> Not only is this a little more verbose than I want but the -f parameter 
>> is a little "brittle" in that there doesn't appear to be any to say 
>> "however many fields there are".
>>
>>
>> _______________________________________________
>> http://www.ntlug.org/mailman/listinfo/discuss
>>
>>   
>>     
>
>
> _______________________________________________
> http://www.ntlug.org/mailman/listinfo/discuss
>
>   




More information about the Discuss mailing list