-1

I have this kind of input in a bash I'm creating:

cat-dog-lion

I need my program to do something with each word like this

`if first_word == "cat" 
 do stuff 
    if second_word == "dog" 
    do other stuff`

How should I do this? Thank you

Lanodisoft
  • 37
  • 4

2 Answers2

0

BASH solution:

input='cat-dog-lion'
if [[ "${input}" =~ "^cat-?" ]]
then
  echo "do stuff"
  if [[ "${input}" =~ "^cat-dog-?" ]]
  then
    echo "do other stuff"
  fi
fi

If wanna AWK solution here it is:

awk -F'-' '{ if ($1=="cat") { print("do stuff"); if ($2=="dog") print("do other stuff"); } }'

Test:

$ echo 'cat-dog-lion' | awk -F'-' '{ if ($1=="cat") { print("do stuff"); if ($2=="dog") print("do other stuff"); } }'
do stuff
do other stuff
$ echo 'cat-wolf-lion' | awk -F'-' '{ if ($1=="cat") { print("do stuff"); if ($2=="dog") print("do other stuff"); } }'
do stuff
$ echo 'lynx-dog-lion' | awk -F'-' '{ if ($1=="cat") { print("do stuff"); if ($2=="dog") print("do other stuff"); } }'
$
Kubator
  • 1,243
  • 2
  • 13
-1

If the input field separator is a -, you should call read with IFS set appropriately:

echo 'cat-dog-lion' | { IFS=- read first_word second_word third_word other_stuff
case $first_word in
cat) ... ;;
*)   ... ;;
esac
case $second_word in
...
esac
...
}

Note that the enclosing { and } are important, as the variables go out of scope after the closing {. (The pipe creates a subprocess in which the variables exist.)

William Pursell
  • 174,418
  • 44
  • 247
  • 279