簡體   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