Shell script: how to read only a portion of text from a variable

777 views Asked by At

I'm developing a little script using ash shell (not bash).

Now i have a variable with the following composition:

VARIABLE = "number string status"

where number could be any number (actually between 1 and 18 but in the future that number could be higher) the string is a name and status is or on or off The name usually is only lowercase letter.

Now my problem is to read only the string content in the variable, removing the number and the status.

How i can obtain that?

4

There are 4 answers

0
Callie J On BEST ANSWER

Two ways; one is to leverage $IFS and use a while loop - this will work for a single line quite happily - as:

echo "Part1 Part2 Part3" | while read a b c
do
    echo $a
done

alternatively, use cut as follows:

a=`echo $var | cut -d' ' -f2`
echo $a
0
Vijay On

How about :

name=$(echo "$variable" | awk '{print $2}')
3
Oliver Charlesworth On

How about using cut?

name=$(echo "$variable" | cut -d " " -f 2)

UPDATE

Apparently, Ash doesn't understand $(...). Hopefully you can do this instead:

name=`echo "$variable" | cut -d " " -f 2`
0
Bastian Bittorf On
#!/bin/sh
myvar="word1 word2 word3 wordX"
set -- $myvar

echo ${15}    # outputs word 15