bash - 使用 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
这里有什么建议可以为带有打印文件名标题的多个文件实现它吗?
解决方案
使用 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
推荐阅读
- linux - Bash 检查用户是否存在,如果存在,将数字添加到用户名
- android - conflict between fragments inside a viewpager
- python - 为python字典中的所有键添加新键
- sql - 如何使 postgres 快速搜索
- javascript - 在已经存在的 objectStore 上创建索引
- windows - 如何使用带有选项运行的任务计划程序运行批处理文件,无论是否登录
- python-3.x - 熊猫合并语句没有给我数据框之间的区别?
- c++ - 贪吃蛇游戏 - 食物牌的随机数生成器
- git - VS Code 跟踪更改为错误的 Repo
- javascript - javascript-比较数组中的两个字符串以查看它们是否相等