[英]To check if a variable in Unix contains any of the string mentioned in a file bash shell
我有一個用例,其中一個變量需要在OR條件中用多個子字符串進行檢查並產生輸出; 如下:
if [ ! -z "$var" ]; then
if [[ $var =~ .*Focus.* ]] || [[ $var =~ .*Wallet.* ]]; then
ser=`echo $var|cut -d ' ' -f 2`
echo " $ser is correct"
else
ser=`echo $var|cut -d ' ' -f 2`
echo "!!!! $ser is incorrect !!!!"
fi
fi
var
包含pid和ServiceName。 正在檢查ServiceName是否包含兩個子字符串中的任何一個。 它運行得很好。 但我希望改為在文件中提到的子字符串列表中檢查var
,以便以后可以修改該文件以獲取更多子字符串。
參數匹配可以使用擴展模式:
#! /bin/bash
check=$(tr '\n' '|' < list_of_terms.txt)
check="@(${check%|})"
for service in Service1 GetFocus WalletLost ; do
if [[ $service == *$check* ]] ; then
echo $service matches
fi
done
希望這段代碼對您有所幫助。
#!/bin/bash
file="/path/to/substring/file"
if [ ! -z "$var" ]; then
while IFS= read -r line
do
if [[ $var == *"$line"* ]]; then
echo "match: $line"
break
fi
done <"$file"
fi
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.