給定一個單詞以空格分隔的句子,我將如何找到單詞第一次出現的位置?
例如“花”的索引
sentence="That's a lovely flower you've got over there! Can i have a smell?"
應該是 4
uj5u.com熱心網友回復:
使用awk和設定記錄分隔符作為欄位分隔符
awk -v p='flower' 'BEGIN {RS=FS} $0 ~ p {print NR}' <<<"$sentence"
4
如果您不打算使用正則運算式,例如
awk -v p='[Ff]lower' ...
或者
awk -v p='smell[:punct:]*' ...
允許標點符號,然后你可以像@karakfa 建議的那樣檢查相等性
awk -v p='flower' 'BEGIN {RS=FS} $0==p {print NR}'
另外,如果您只想第一次出現,請添加 exit
... {print NR; exit}'
uj5u.com熱心網友回復:
與sed:
sed 's/ /\n/g' <<<"$sentence" | sed -n "/flower/="
輸出:
4
uj5u.com熱心網友回復:
您可以使用引數擴展洗掉字串的其余部分以獲得第一個單詞,將其與搜索詞進行比較,并使用引數擴展從字串中洗掉第一個單詞。
#! /bin/bash
search=flower
sentence="That's a lovely flower you've got over there! Can i have a smell?"
i=1
while [[ $sentence = *' '* ]] ; do
if [[ $search = ${sentence%% *} ]] ; then # Remove from the first space.
echo $i
break
fi
sentence=${sentence#* } # Remove the first word.
(( i ))
done
或者,您可以使用單詞填充陣列并遍歷陣列:
read -ra words <<< "$sentence"
for i in "${!words[@]}" ; do
if [[ ${words[i]} = $search ]] ; then
echo $(( i 1 ))
break
fi
done
或者,您可以選擇單詞之前的部分,計算其中的空格(通過洗掉所有不是空格的內容并檢查剩余字串的長度)并添加 2。
before=${sentence% $search *}
if [[ $before = $sentence ]] ; then
echo Not found >&2
else
spaces=${before//[^ ]}
echo $(( 2 ${#spaces} ))
fi
或者...
uj5u.com熱心網友回復:
使用多種工具...
$ echo "$sentence" | tr ' ' \\n | grep -nxF flower | cut -d: -f1
4
uj5u.com熱心網友回復:
試試這個,使用 grep 與 head 和 awk 的組合
grep 'flower' sampl.txt|head -1| awk '{split($0,data," ");for (word in data) {if (data[word]~/flower/){print word; break;}}}'
uj5u.com熱心網友回復:
與 GNU sed
sed '/\bflower\b.*/!d;s///;s/[^ ]//g' <<< "$sentence" | wc -c
這假設兩個單詞之間正好有一個空格,并且$sentence.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/392374.html
標籤:猛击
下一篇:將echo中的通配符擴展到檔案
