16

別の for ループなど、追加のコードを追加せずにこれを実行しようとしています。文字列と配列を比較する正論理を作成できます。負の論理が必要で、配列にない値のみを出力したいのですが、基本的にこれはシステム アカウントを除外するためです。

私のディレクトリには、次のようなファイルがあります。

admin.user.xml 
news-lo.user.xml 
system.user.xml 
campus-lo.user.xml
welcome-lo.user.xml

これは、そのファイルがディレクトリにある場合に肯定的な一致を行うために使用したコードです。

#!/bin/bash

accounts=(guest admin power_user developer analyst system)

for file in user/*; do

    temp=${file%.user.xml}
    account=${temp#user/}
    if [[ ${accounts[*]} =~ "$account" ]]
    then
        echo "worked $account";
    fi 
done

正しい方向への助けをいただければ幸いです、ありがとう。

4

2 に答える 2

24

肯定的な一致の結果を否定できます。

if ! [[ ${accounts[*]} =~ "$account" ]]

また

if [[ ! ${accounts[*]} =~ "$account" ]]

ただし、$account「user」に等しい場合は、「power_user」の部分文字列と一致するため、一致することに注意してください。明示的に反復するのが最善です:

match=0
for acc in "${accounts[@]}"; do
    if [[ $acc = "$account" ]]; then
        match=1
        break
    fi
done
if [[ $match = 0 ]]; then
    echo "No match found"
fi
于 2013-04-09T12:02:27.987 に答える
0

以下は完全一致でも機能します

if echo "${accounts[*]}"|egrep -q "\b$account}\b"; then ...
于 2021-12-20T11:22:02.997 に答える