如何判断一个字符串是否包含Unix shell脚本中的另一个字符串?
发布时间:2020-12-15 16:38:38 所属栏目:安全 来源:网络整理
导读:我想写一个Unix shell脚本,如果在另一个字符串内部有一个字符串,它会做各种逻辑。例如,如果我在某个文件夹,分支。有人可以告诉我如何完成这个吗?如果可能,我想让这不是shell具体(即不是bash只)但如果没有其他方式,我可以做到这一点。 #!/usr/bin/env
我想写一个Unix shell脚本,如果在另一个字符串内部有一个字符串,它会做各种逻辑。例如,如果我在某个文件夹,分支。有人可以告诉我如何完成这个吗?如果可能,我想让这不是shell具体(即不是bash只)但如果没有其他方式,我可以做到这一点。
#!/usr/bin/env sh if [ "$PWD" contains "String1" ] then echo "String1 present" elif [ "$PWD" contains "String2" ] then echo "String2 present" else echo "Else" fi
这里是另一个解决方案。这使用
POSIX substring parameter expansion,所以它工作在bash,dash,ksh …
test "${string#*$word}" != "$string" && echo "$word found in $string" 编辑:这是一个好主意,C.罗斯。这里是一个功能版本有一些例子: # contains(string,substring) # # Returns 0 if the specified string contains the specified substring,# otherwise returns 1. contains() { string="$1" substring="$2" if test "${string#*$substring}" != "$string" then return 0 # $substring is in $string else return 1 # $substring is not in $string fi } contains "abcd" "e" || echo "abcd does not contain e" contains "abcd" "ab" && echo "abcd contains ab" contains "abcd" "bc" && echo "abcd contains bc" contains "abcd" "cd" && echo "abcd contains cd" contains "abcd" "abcd" && echo "abcd contains abcd" contains "" "" && echo "empty string contains empty string" contains "a" "" && echo "a contains empty string" contains "" "a" || echo "empty string does not contain a" contains "abcd efgh" "cd ef" && echo "abcd efgh contains cd ef" contains "abcd efgh" " " && echo "abcd efgh contains a space" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- Vim:在可视块模式下快速选择矩形文本块
- bash – 如何通过Cygwin在Windows 7上运行.sh文件?
- 单元测试 – 如何在karma angularjs中对setInterval进行单元
- scala – 在编译期间SBT中的StackOverflowError
- vim quickfix避免缓冲区更改
- typescript – RXJS Observable doSomething onComplete
- angularjs – 如何使用Angulartics在Google Analytics中设置
- 做Docker Inspect时如何获得ENV变量
- vimの学习笔记 删除方法
- 为什么scala的模式加工在类型匹配的for循环中不起作用?