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

Zub*_*air 38 linux shell

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

a="The cat sat on the mat"
Run Code Online (Sandbox Code Playgroud)

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

gle*_*man 66

随着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
Run Code Online (Sandbox Code Playgroud)

  • @ Zubair,bash 2.0已有10年历史,并且有两个主要版本(http://ftp.gnu.org/gnu/bash/).你能更新一下吗? (8认同)
  • +1它也适用于Dash,ash,ksh,pdksh,zsh.短划线和灰烬想要`["$ x"="$ 1"]`和pdksh想要`x = $ 2; 然而,x ="$ {1 %% $ x*}". (7认同)
  • 这太棒了。第一个参数替换表达式表示“从搜索表达式删除到末尾”,${#x} 是剩余的长度 - 这是搜索表达式的位置! (3认同)

Cer*_*lla 26

您可以使用grep来获取字符串匹配部分的字节偏移量:

echo $str | grep -b -o str
Run Code Online (Sandbox Code Playgroud)

根据你的例子:

[user@host ~]$ echo "The cat sat on the mat" | grep -b -o cat
4:cat
Run Code Online (Sandbox Code Playgroud)

如果你只是想要第一部分,你可以把它传递给awk

echo $str | grep -b -o str | awk 'BEGIN {FS=":"}{print $1}'
Run Code Online (Sandbox Code Playgroud)

  • 在我的Mac上输出'0:cat' (11认同)
  • `cut -d:-f1`比通过awk管道轻一点 (7认同)
  • @Zubair:定义"不起作用" - 我的机器输出正确. (3认同)

Nik*_*bak 6

我用awk这个

a="The cat sat on the mat"
test="cat"
awk -v a="$a" -v b="$test" 'BEGIN{print index(a,b)}'
Run Code Online (Sandbox Code Playgroud)


qbe*_*220 5

echo $a | grep -bo cat | sed 's/:.*$//'
Run Code Online (Sandbox Code Playgroud)

  • @Zubair - 你的命令在我的Ubuntu 10.04盒子上显示"4".这就是我的期望. (2认同)