Helpful Information
 
 
Category: UNIX Help
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....

taking input from a file you could use:


while (read word); do
(process the word here)
done < filename

(untested, didīt do any bash for quite some time...)

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.

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 (href="http://db.ilug-bom.org.in/Documentation/abs-guide/string-manipulation.html)

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

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










privacy (GDPR)