繁体   English   中英

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

[英]Position of a string within a string using Linux shell script?

如果我在 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

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

echo $str | grep -b -o str

根据您的示例:

[user@host ~]$ echo "The cat sat on the mat" | grep -b -o cat
4:cat

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

echo $str | grep -b -o str | awk 'BEGIN {FS=":"}{print $1}'

我为此使用了awk

a="The cat sat on the mat"
test="cat"
awk -v a="$a" -v b="$test" 'BEGIN{print index(a,b)}'
echo $a | grep -bo cat | sed 's/:.*$//'

这可以使用ripgrep (又名rg )来完成。

❯ a="The cat sat on the mat"
❯ echo $a | rg --no-config --column 'cat'
1:5:The cat sat on the mat
❯ echo $a | rg --no-config --column 'cat' | cut -d: -f2
5

如果你想让它成为一个函数,你可以这样做:

function strindex() {
    local str=$1
    local substr=$2
    echo -n $str | rg --no-config --column $substr | cut -d: -f2
}

...并使用它: strindex <STRING> <SUBSTRING>

strindex "The cat sat on the mat" "cat"
5

您可以使用以下ripgrep在 MacOS 上brew install --formula ripgrepbrew install --formula ripgrep

这只是 glenn jackman 的答案的一个版本,其中转义了*

strpos() { 
  haystack=$1
  needle=${2//\*/\\*}
  x="${haystack%%$needle*}"
  [[ "$x" = "$haystack" ]] && echo -1 || echo "${#x}"
}

strrpos() { 
  haystack=$1
  needle=${2//\*/\\*}
  x="${haystack%$needle*}"
  [[ "$x" = "$haystack" ]] && echo -1 || echo "${#x}"
}

最简单的是 - expr index "The cat sat on the mat" cat

它会返回 5

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM