首页 > 解决方案 > 使用 bash 脚本在多个文件中搜索用户名并打印如果它不存在

问题描述

我有一个由多个用户组成的文件,我需要将其与多个文件进行比较,并在具有文件名的文件中不存在任何特定用户时打印。

#!/bin/bash
awk '{print $1}' $1 | while read -r line; do
if ! grep -q "$line" *.txt;
then
echo "$line User doesn't exist"
fi
done

在上面的脚本中,将 user_list 文件作为 $1 传递,可以找到单个目标文件的用户,但对于多个文件则失败。

文件内容:

user_list:
Johnny
Stella
Larry
Jack

One of the multiple files contents:
root:x:0:0:root:/root:/bin/bash
Stella:x:1:1:Admin:/bin:/bin/bash
Jack:x:2:2:admin:/sbin:/bin/bash

用法:

./myscript user_list.txt

期望的输出:

File1:
Stella doesn't exist
Jack doesn't exist

File2:
Larry doesn't exist
Johnny doesn't exist

这里有什么建议可以为带有打印文件名标题的多个文件实现它吗?

标签: bashshell

解决方案


使用 for 循环遍历每个文件并分别为每个文件执行代码。

#!/bin/bash
for f in *.txt; do
    echo $f:
    awk '{print $1}' $1 | while read -r line; do
        if ! grep -q "$line" $f
        then
            echo "$line doesn't exist"
        fi
    done
    echo 
done

推荐阅读