Linux 中如何搜索文本文件中的每个匹配项?

Linux 中如何搜索文本文件中的每个匹配项?

我有 23 个字符串要搜索,我希望它返回文件中的那些字符串。

我得到了下面的代码:

users='User1\|User2\|User3\|User4\|User5\|User6\|User7\|User8\|User9\|User10\|User11\|User12..User23'

期望的输出:

User1 is in the file
User2 is not in the file
...
User 23 is in the file

我不知道如何做到这一点,我正在思考一个数组,但是,如果可能的话,我想要一些提示。提前致谢。

答案1

使用数组:

users=(User1 User2 User3 User4) # et cetera
for i in "${users[@]}"; do
    echo -n "$user is "
    if grep -q "$user" inputfile; then
        echo "present"
    else
        echo "not present"
    fi
done

grep -q将执行搜索但不返回任何输出,允许您在if测试中静默使用它。

或者,您可以将每个用户放在名为 的文件中Users,然后:

grep -o -f Users inputfile

这将输出看到的所有用户的列表。如果您想查看当前和缺席的用户,您可以:

echo "Users present:"
grep -o -f Users inputfile
echo "Users absent:"
grep -vo -f Users inputfile

答案2

尝试这个,

users=( User1 User2 User3 User4 )
for i in "${users[@]}"
do
   grep -qw $i file && echo "$i is in the file" || echo "$i is not in the file"
done

man

-q,--安静,--沉默

安静的;不要向标准输出写入任何内容。如果发现任何匹配项,即使检测到错误,也会立即以零状态退出。

答案3

进一步调整。

users=( User1 User2 User3 User4 )
for i in "${users[@]}"
do
   echo "$i is" $(grep -qw $i file || echo "not") "in the file"
done

答案4

只需对文件进行一次扫描:这是 bash

# the array of user names
users=( User{1..23} )
# an array of grep options: ( -e User1 -e User2 ...)
for u in "${users[@]}"; do grep_opts+=( -e "$u" ); done
# scan the input file and save the user names that are present in the file
readarray -t users_present < <(grep -Fo "${grep_opts[@]}" input | sort -u)
# find the user names absent from the file
# this assumes there are no spaces in any of the user names.
for u in "${users[@]}"; do
     [[ " ${users_present[*]} " == *" $u "* ]] || users_absent+=( "$u" )
done
# and print out the results
printf "%s is in the file\n" "${users_present[@]}"
printf "%s is NOT in the file\n" "${users_absent[@]}"

相关内容