Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Split variable

Status
Not open for further replies.

tempest92

Technical User
Sep 16, 2003
110
GB
hi, can someone help please !

i have a variable in a script that contains -

name1,name2,name3,name4

i want to split it into as many variables as there are fields i.e.

var1=name1
var2=name2
var3=name3
var4=name4
etc.

thanks !!
 
HI,
Code:
IFS=,
V1=name1,name2,name3,name4
set $V1  # set arguments $1 $2 according to the content of V1
while [ $# -ne 0 ]
do
  echo $1
  shift
done
 
Isn't that

Code:
set -- $V1  # set arguments $1 $2 ... according to the content of V1


HTH,

p5wizard
 
You could also do it this way;

IFS=","
count=0

for person in `cat file1` ; do
eval name${count}=$person
count=$(($count+1))
done

But this is a UUOC.

I'm sure that someone will give you an awk one liner. Step forward PHV / Feherke / Anni.

Alan
 
Hi

I would say nothing for the [tt]cat[/tt] in this case, but that incrementing...
Code:
for person in [red]$(<derfile)[/red]; do
  eval name${count}=$person
  [red]((count++))[/red]
done
Note that inside the double parenthesis ( () ) the variables are expanded automatically and is faster to just let it happen. I mean, do not put dollar sign ( $ ) in fron t of variable names inside the double parenthesis.
Bash:
[blue]master #[/blue] time while ((count<100000)); do ((count++)); done
real    0m11.472s
user    0m5.500s
sys     0m4.609s

[blue]master #[/blue] time while ((count<100000)); do count=$(($count+1)); done
real    0m16.362s
user    0m7.890s
sys     0m4.359s
Code:
[blue]master #[/blue] time while ((count<100000)); do ((count++)); done
    0.90s real     0.89s user     0.00s system

[blue]master #[/blue] time while ((count<100000)); do count=$(($count+1)); done
    1.02s real     1.01s user     0.00s system

Feherke.
 
Hi,

You are right P5wizard, if V1 contains some leading '-', they may influnece setting and are lost as chars.
Code:
set -- V1 # is more secure
 
There you did it again... ;-)

Fat finger syndrome or hypocafeinia?

p5

HTH,

p5wizard
 
hi,

IFS=,
V1=name1,name2,name3,name4
set -- $V1 # set arguments $1 $2 according to the content of V1
while [ $# -ne 0 ]
do
echo $1
shift
done

the above worked fine.

i am now running a command that returns to values in 1 variable that look like -

V1=name1 name2

i tried removing IFS and IFS=' ' but i just get name1 name2 twice

thanks !
 
Hi

The [tt]IFS[/tt] holds a list of all separator characters. If you add both comma ( , ) and space ( ), then your string will be split on whichever is encountered.
Code:
IFS=', '

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top