检查文件bash中是否存在特定字符串
我想写一个脚本来检查副本 例如:我有一个文本文件,其中的信息格式为/etc/passwd检查文件bash中是否存在特定字符串,bash,search,string,full-text-search,pattern-matching,Bash,Search,String,Full Text Search,Pattern Matching,我想写一个脚本来检查副本 例如:我有一个文本文件,其中的信息格式为/etc/passwd alice:x:1008:555:William Williams:/home/bill:/bin/bash bob:x:1018:588:Bobs Boos:/home/bob:/bin/bash bob:x:1019:528:Robt Ross:/home/bob:/bin/bash james:x:1012:518:Tilly James:/home/bob:/bin/bash 我只想检查是否有重复
alice:x:1008:555:William Williams:/home/bill:/bin/bash
bob:x:1018:588:Bobs Boos:/home/bob:/bin/bash
bob:x:1019:528:Robt Ross:/home/bob:/bin/bash
james:x:1012:518:Tilly James:/home/bob:/bin/bash
我只想检查是否有重复的用户,如果有,将该行输出为标准错误。因此,在上面的示例中,由于bob出现两次,因此我的输出将生成如下内容:
Error duplicate user
bob:x:1018:588:Bobs Boos:/home/bob:/bin/bash
bob:x:1019:528:Robt Ross:/home/bob:/bin/bash
现在我有一个while循环,它读取每一行,并使用awk-F将每一条信息存储在一个变量中,该变量以“:”分隔。存储用户名后,我不太确定检查用户名是否已经存在的最佳方法
我的代码的某些部分:
while read line; do
echo $line
user=`echo $line | awk -F : '{print $1}'`
match=`grep $user $1`($1 is the txtfile)
if [ $? -ne 0 ]; then
echo "Unique user"
else
echo "Not unique user"
then somehow grep those lines and output it
fi
done
匹配不会产生正确的结果建议?不要重新发明轮子,而是使用以下工具:
提取第一个字段cut
和sort
仅保留重复的行uniq
cut -d : -f 1 | sort | uniq -d | while read i ; do echo "error: duplicate user $i" done
提取第一个字段cut
和sort
仅保留重复的行uniq
cut -d : -f 1 | sort | uniq -d | while read i ; do echo "error: duplicate user $i" done
- 听起来像是awk的工作对我来说:
% awk -F':' '
/:/ {
count[$1] += 1
}
END {
for (user in count) {
if (count[user] > 1) {
print user " appears in the file " count[user] " times."
}
}
}
' /etc/passwd
对我来说,听起来像是awk的工作:
% awk -F':' '
/:/ {
count[$1] += 1
}
END {
for (user in count) {
if (count[user] > 1) {
print user " appears in the file " count[user] " times."
}
}
}
' /etc/passwd
perl提案:
perl -F: -lanE 'push @{$h{$F[0]}},$_; END{for $k (keys %h){if(@{$h{$k}}>1){say "Error";say for @{$h{$k}}}}}' file
perl提案:
perl -F: -lanE 'push @{$h{$F[0]}},$_; END{for $k (keys %h){if(@{$h{$k}}>1){say "Error";say for @{$h{$k}}}}}' file
grep
仅在不匹配时返回非零退出代码。grep
仅在不匹配时返回非零退出代码。