-1

When the user inputs FRUIT=apple in the Unix shell, how can I get the name FRUIT and apple from the input FRUIT=apple separately?

echo -e "\nEnter inputs here: \c"
read inputs

## user input "FRUIT=apple"

Is there any way to get a partial text from the input? Can we use the expr command to solve the problem? If so, how?

3 Answers3

2

You can do it this way, for example:

$ IFS== read -r key value
FRUIT=apple
$ echo "$key"
FRUIT
$ echo "$value"
apple
l0b0
  • 55,365
  • 30
  • 138
  • 223
2

Try using cut command and pass the delimiter as "=" . The right side of the same will be apple and left side will be FRUIT.

cat file_name | cut -d "=" -f1
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
2

You could use expr with regular expressions like this:

$ str='FRUIT=apple'
$ key=$(expr "$str" : '\([^=]*\)')
$ value=$(expr "$str" : '.*=\([^=]*\)')
$ echo "<$key> <$value>"
<FRUIT> <apple>

The expression expr string : regex returns the number of characters matched, or (as used above) if there is a capture group \(...\), it'll return that capture group. The regex starts with an implicit ^ anchor.

The expression for key matches everything up to the first = sign; the one for value captures everything after the (last) = sign.


All this being said, expr is a holdover from when shells weren't powerful enough to do text processing using built-ins; any modern shell can do it. For example:

  • Splitting on = and reading into two variables:

    IFS='=' read -r key value <<< "$str"
    
  • Using parameter expansion:

    key=${str%=*}
    value=${str#*=}
    
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116