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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Divide string into seperate entries 4

Status
Not open for further replies.

TSch

Technical User
Jul 12, 2001
557
DE
Hi folks,

I'm facing the following challenge:

There's a file containing a string looking like that:

203;202;204;205;207;206;208

The length of this string is changing from time to time.

Now what I'd like to do is to separate this string like this:

203
202
204
205
207
206
208

And perform certain actions on each of those numbers ...

Any idea what would be an elegant way to accomplish this ?

Regards
Thomas
 
A starting point:
Code:
tr ';' '\n' </path/to/input >output

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Hi

Supposing $str holds your input string and taking your request literally :
Code:
echo [green][i]"$str"[/i][/green] [teal]|[/teal] tr [green][i]';'[/i][/green] [green][i]'[/i][/green][lime][i]\n[/i][/lime][green][i]'[/i][/green]
Personally I would simply [tt]read[/tt] it into an array. But this works only with [tt]bash[/tt] :
Bash:
[blue]IFS[/blue][teal]=[/teal][green][i]';'[/i][/green] [COLOR=chocolate]read[/color] -a x [teal]<<<[/teal] [green][i]"$str"[/i][/green]
Or would just loop through it. This works in [tt]bash[/tt] and [tt]ksh[/tt] too ( notice the semicolon ( ; ) after the $str ) :
Code:
[b]while[/b] [COLOR=chocolate]read[/color] -d [green][i]';'[/i][/green] x[teal];[/teal] [b]do[/b]
  echo [green][i]"$x"[/i][/green][teal];[/teal]
[b]done[/b] [teal]<<[/teal]ENDOFTEXT
[navy]$str[/navy][teal];[/teal]
ENDOFTEXT
Another way would be to "consume" the string piece by piece ( notice again the necessity of trailing semicolon ) :
Code:
[navy]str[/navy][teal]=[/teal][green][i]"$str;"[/i][/green]
[b]while[/b] [teal][[[/teal] [green][i]"$str"[/i][/green] [teal]]];[/teal] [b]do[/b]
  echo [green][i]"${str%%;*}"[/i][/green]
  [navy]str[/navy][teal]=[/teal][green][i]"${str#*;}"[/i][/green]
[b]done[/b]

Feherke.
 
Thanks a lot for the quick responses !
That was exactly what I needed.
 
Another one using IFS...
Code:
#!/bin/ksh

STRING="203;202;204;205;207;206;208"

IFS=';'

for NUM in ${STRING}
do
    print "Numer is: ${NUM}"
done
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top