linux - 使用 Linux shell 脚本在字符串中的位置?

标签 linux shell

如果我在 shell 变量中有文本,说 $a:

a="The cat sat on the mat"

如何使用 Linux shell 脚本搜索“cat”并返回 4,如果未找到则返回 -1?

最佳答案

使用 bash

a="The cat sat on the mat"
b=cat
strindex() { 
  x="${1%%"$2"*}"
  [[ "$x" = "$1" ]] && echo -1 || echo "${#x}"
}
strindex "$a" "$b"   # prints 4
strindex "$a" foo    # prints -1
strindex "$a" "ca*"  # prints -1

关于linux - 使用 Linux shell 脚本在字符串中的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5031764/

相关文章:

linux - Linux 中 tcpip 堆栈的多个实例

c - pthread(段错误)

Linux:上传未完成的文件-进行文件大小检查(scp/rsync)

python - 如何使用gcc在windows for linux上进行跨平台编译?

linux - 将 shell 变量传递给系统用户

mysql - Debian 10 MariaDB 'Can' t 通过套接字 '/var/run/mysqld/mysqld.sock' (2)' 连接到本地 MySQL 服务器

windows - 如何在 Windows 下将参数传递给 .sh 脚本?

shell - 如何检查声音是否在我的声卡上停止播放

regex - Linux命令sed中的正则表达式

linux - 根据用户输入的文件映射