使用Linux Shell脚本,字符串在字符串中的位置? [英] Position of a string within a string using Linux shell script?

查看:299
本文介绍了使用Linux Shell脚本,字符串在字符串中的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在shell变量中包含文本,请说$a:

If I have the text in a shell variable, say $a:

a="The cat sat on the mat"

如何搜索"cat"并使用Linux Shell脚本返回4,如果找不到则返回-1?

How can I search for "cat" and return 4 using a Linux shell script, or -1 if not found?

推荐答案

使用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

这篇关于使用Linux Shell脚本,字符串在字符串中的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆