|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
String manipulation
I m compiling using bourne shell.My question is how to divide a string into several variables?
Example: "I have a question" divide into "I" "have" "a" "question" Thanks for reading.... |
|
#2
|
|||
|
|||
|
taking input from a file you could use:
Code:
while (read word); do (process the word here) done < filename (untested, didīt do any bash for quite some time...)
__________________
-- Manuel Hirsch - Linux, FreeBSD, programming, administration articles, tutorials and more. |
|
#3
|
|||
|
|||
|
might want to learn awk
chance@localhost>echo I have a question | awk '{print $1}' I chance@localhost>echo I have a question | awk '{print $2}' have chance@localhost>echo I have a question | awk '{print $3}' a chance@localhost>echo I have a question | awk '{print $4}' question I think it will do tons more, but this type thing is all I've ever used it for. |
|
#4
|
|||
|
|||
|
or you could use bash's builtins
stringZ=abcABC123ABCabc # |----| # |----------| echo ${stringZ#a*C} # 123ABCabc # Strip out shortest match between 'a' and 'C'. echo ${stringZ##a*C} # abc # Strip out longest match between 'a' and 'C'. More info here |
|
#5
|
|||
|
|||
|
I think this is simplest:
var1="I have a question" set `echo var1` After that code executes, each word will be assigned to $1 $2 $3 $4. So, the following command: echo $2 would produce this output: have |
|
#6
|
|||
|
|||
|
You could use the cat/cut command for static and standard inputs. But if u have varying input, you might wanna have a loop that loops through the number of words entered.
#bin/sh read input echo $input > test w1=`cat test | cut -d " " -f 1` w2=`cat test | cut -d " " -f 2` w3=`cat test | cut -d " " -f 3` w4=`cat test | cut -d " " -f 4` echo "$w1 \n" echo "$w2 \n" echo "$w3 \n" echo "$w4 \n" Gd Luck |
![]() |
| Viewing: Dev Shed Forums > Operating Systems > UNIX Help > String manipulation |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|
|