Linux Shell 脚本 - 带通配符的字符串比较

标签 linux string shell sh

我正在尝试查看一个字符串是否是 shell 脚本 (#!bin/sh) 中另一个字符串的一部分。

我现在的代码是:

#!/bin/sh
#Test scriptje to test string comparison!

testFoo () {
        t1=$1
        t2=$2
        echo "t1: $t1 t2: $t2"
        if [ $t1 == "*$t2*" ]; then
                echo "$t1 and $t2 are equal"
        fi
}

testFoo "bla1" "bla"

我正在寻找的结果是,我想知道“bla1”中何时存在“bla”。

谢谢和亲切的问候,

更新: 我已经尝试了此处描述的“包含”功能:How do you tell if a string contains another string in Unix shell scripting?

以及 String contains in bash 中的语法

但是,它们似乎与普通的 shell 脚本 (bin/sh) 不兼容...

帮忙吗?

最佳答案

在 bash 中使用 ==!= 时,您可以这样写:

if [[ $t1 == *"$t2"* ]]; then
    echo "$t1 and $t2 are equal"
fi

请注意,星号位于引号的外侧,通配符模式必须位于右侧。

对于/bin/sh,= 运算符仅用于相等,而不用于模式匹配。不过,您可以使用 case 进行模式匹配:

case "$t1" in
    *"$t2"*) echo t1 contains t2 ;;
    *) echo t1 does not contain t2 ;;
esac

如果您专门针对 Linux,我假设存在/bin/bash。

关于Linux Shell 脚本 - 带通配符的字符串比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19891491/

相关文章:

linux - 如何实现最佳的 tcpip 套接字数据速率性能

linux - dlang是否默认安装一些信号处理程序

linux - 在 ubuntu 中使用互联网设置 NTP 服务器

python - 多行字符串的正确缩进?

linux - 奇怪的 Nasm 错误 : invalid combination of opcode and operands

c - 为什么这个链表初始化不起作用?

c++ - 代码输出随机符号,我不确定出了什么问题

php - 使用 shell 脚本将 CSV 文件上传到数据库显示错误

python - 如何拆分特定范围内的列?

linux - 如何在 linux 中的 tcsh shell 上执行此操作