Breaking a String into Four Different Numbers 

Question:
I'm having trouble breaking a string into four different numbers. What I'm starting out with is

foo='1218141 1441 1664 122222'

and what I want to have is

a=1218141
b=1441
c=1664
d=122222

I'm tried using some pattern matching to break the string up into these four different variables, but the only way I've been able to accomplish this has been with significantly more code than is absolutely necessary. There has to be an easier way to do this.

Use ksh:

Code:
$ foo='1218141 1441 1664 122222'
$ echo $foo
1218141 1441 1664 122222
$ echo $foo | read a b c d
$ echo $a
1218141
$ echo $b
1441
$ echo $c
1664
$ echo $d
122222
$

---- or 

Or use ordinary bash and avoid the extra pipe and process:
Code:
foo='1218141   1441  1664  122222'
read A B C D <<< "$foo"
echo $A
echo $B
echo $C
echo $D

--- or

Here's one a bit more generic solution using bash's array capabilities:

Code:
declare -a A; export A
FOO="one two three four"
IND=0
set $FOO #break up the string
while test ! -z $1
do
  A[$IND]=$1; shift
  IND=$(($IND + 1))
done
echo ${A[0]}, ${A[3]} #just a test sample...The idea is to use the shell's capability of splitting strings into positional parameters, and then simply loop over them, inserting each value into the array.

--- or

If we use arrays there are also more direct ways of assigning, like 

Code:
foo='1218141 1441 1664 122222'
typeset -a bar=($foo)We can then use the individual array elements:

Code:
echo ${bar[0]}
echo ${bar[1]}
echo ${bar[2]}
echo ${bar[3]}or e.g.

Code:
for i in ${bar[@]}; do 
  echo $i
doneor e.g.

Code:
for ((i=0; i<${#bar[@]};i++)); do
   echo ${bar[i]}
done

Have a Unix Problem
Unix Forum - Do you have a UNIX Question?

Unix Books :-
UNIX Programming, Certification, System Administration, Performance Tuning Reference Books

Return to : - Unix System Administration Hints and Tips

(c) www.gotothings.com All material on this site is Copyright.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
All product names are trademarks of their respective companies.
The site www.gotothings.com is in no way affiliated with or endorsed by any company listed at this site.
Any unauthorised copying or mirroring is prohibited.