首页 > 解决方案 > 重击。读取符号之间的输入“单词”字符串

问题描述

我在创建的 bash 中有这种输入:

猫狗狮子

我需要我的程序对每个单词做一些这样的事情

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

我该怎么做?谢谢

标签: linuxbashshell

解决方案


BASH 解决方案:

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

如果想在这里使用 AWK 解决方案:

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

测试:

$ 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"); } }'
$

推荐阅读