假設我有一個字串,
a="This is a string"
和一個陣列,
b=("This is my" "sstring")
我想執行的if,如果任何子條件a在于b這是真實的,因為“這是”是第一要素的子串b。
如果有兩個字串,我知道如何檢查是否$x是$yusing的子字串,
if [[ $y == *$x* ]]; then
#Something
fi
但由于$x是一個字串陣列,我不知道如何在不必顯式回圈陣列的情況下執行此操作。
uj5u.com熱心網友回復:
這可能就是你所需要的:
$ printf '%s\n' "${b[@]}" | grep -wFf <(tr ' ' $'\n' <<<"$a")
This is my
否則 - shell 是一種用于操作檔案/行程和對工具的序列呼叫的工具。發明 shell 的家伙還發明了 awk,讓 shell 呼叫來操作文本。您要做的是操作文本,因此您很有可能應該使用 awk 而不是 shell 來處理您正在執行的任務,而此任務是其中的一部分。
$ printf '%s\n' "${b[@]}" |
awk -v a="$a" '
BEGIN { split(a,words) }
{ for (i in words) if (index($0,words[i])) { print; f=1; exit} }
END { exit !f }
'
This is my
上面假設a不包含任何反斜杠,如果它可以使用它來代替:
printf '%s\n' "${b[@]}" | a="$a" awk 'BEGIN{split(ENVIRON["a"],words)} ...'
如果中的任何元素b可以包含換行符,則:
printf '%s\0' "${b[@]}" | a="$a" awk -v RS='\0' 'BEGIN{split(ENVIRON["a"],words)} ...'
uj5u.com熱心網友回復:
您可以將其拆分$a為一個陣列,然后回圈兩個陣列以查找匹配項:
a="this is a string"
b=( "this is my" "string")
# Make an array by splitting $a on spaces
IFS=' ' read -ra aarr <<< "$a"
for i in "${aarr[@]}"
do
for j in "${b[@]}"
do
if [[ $j == *"$i"* ]]; then
echo "Match: $i : $j"
break
fi
done
done
# Match: this : this is my
# Match: is : this is my
# Match: string : string
如果您需要處理$a(例如this is,is my等)中的子字串,那么您將需要遍歷陣列,生成所有可能的子字串:
for (( length=1; length <= "${#aarr[@]}"; length )); do
for (( start=0; start length <= "${#aarr[@]}"; start )); do
substr="${aarr[@]:start:length}"
for j in "${b[@]}"; do
if [[ $j == *"${substr}"* ]]; then
echo "Match: $substr : $j"
break
fi
done
done
done
# Match: this : this is my
# Match: is : this is my
# Match: string : string
# Match: this is : this is my
uj5u.com熱心網友回復:
以下是如何將字串 a 中的最大單詞數匹配到陣列 b 的條目:
#!/usr/bin/env bash
a="this is a string"
b=("this is my" "string" )
# tokenize a words into an array
read -ra a_words <<<"$a"
match()
{
# iterate entries of array b
for e in "${b[@]}"; do
# tokenize entry words into an array
read -ra e_words <<<"$e"
# initialize counter/length to the shortest MIN words count
i=$(( ${#a_words[@]} < ${#e_words[@]} ? ${#a_words[@]} : ${#e_words[@]} ))
# iterate matching decreasing number of words
while [ 0 -lt "$i" ]; do
# return true it matches
[ "${e_words[*]::$i}" = "${a_words[*]::$i}" ] && return
# decrease number of words to match
i=$(( i - 1 ))
done
done
# reaching here means no match found, return false
return 1
}
if match; then
printf %s\\n 'It matches!'
fi
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/397186.html
上一篇:如何獲取awk列印函式名稱和注釋
下一篇:提取括號內的單詞并替換成句子
