1

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?

Chris J
  • 30,688
  • 6
  • 69
  • 111
Ivan
  • 4,186
  • 5
  • 39
  • 72

4 Answers4

4

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
Chris J
  • 30,688
  • 6
  • 69
  • 111
3

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`
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • $(...) isn't known to ash. they need to use backticks instead. – Chris J Jan 13 '12 at 23:19
  • Are you sure @ChrisJ? I checked on [wikipedia](http://en.wikipedia.org/wiki/Comparison_of_computer_shells#Inter-process_communication) and it does state that `ash` supports `command substitution`. – jaypal singh Jan 14 '12 at 02:20
  • Could have sworn I tried this last night and `$(...)` threw an error, whilst backticks didn't. It's working this morning. Damned if I know what's going on. {confused} – Chris J Jan 14 '12 at 10:51
1
#!/bin/sh
myvar="word1 word2 word3 wordX"
set -- $myvar

echo ${15}    # outputs word 15
Bastian Bittorf
  • 447
  • 4
  • 6
1

How about :

name=$(echo "$variable" | awk '{print $2}')
Vijay
  • 65,327
  • 90
  • 227
  • 319