修改脚本以从条件中删除 else

Modify script to remove else from condition

我正在尝试使用 while 循环从一个文件中找到几个关键字,然后检查另一个文件中是否存在这些关键字。如果不是,它们应该写在另一个文件中。 下面是我的代码

while read -r line; do
if grep -q -e "$line" $file_name; then
        echo "character found"
else
    echo "$line" >> notfound.txt
fi  
done  < result.txt`

我觉得整个 if 条件可以通过排除 else 部分和 echo "character found" 来简化,因为有很多字符。请帮助删除它。我试过 -v 但不幸的是没有用。

也可以使用 while 循环,从第 3 行开始到之前的 2 行结束

提前致谢!

当然可以在一行中完成,通过在执行时检查命令的 return 代码,请参阅 bash, exit-codes

#!/bin/bash

while read -r line
do

   # On successful search 'grep' returns code '0', negating it for the
   # unsuccessful case to return a 'true' condition

   ! grep -q -e "$line" "$file_name"  && echo "$line" >> notfound.txt

done <result.txt

算了;使用 comm(1) 这就是它的好处。示例:

#!/usr/local/bin/bash

cat >needles <<DONE
p1
n1
p2
n2
DONE

cat >haystack <<DONE
p3
p2
p1
DONE

comm -23 <(sort -u needles) <(sort -u haystack)

假设$filename是一个任意文本文件,result.txt是一个包含单词列表的文件,每行一个。

#!/bin/bash

# 1. get the list of words found in the file, store in an array
mapfile -t found < <(grep -owFf result.txt "$filename" | sort -u)

# 2. get the list of words not found
grep -vxFf <(printf "%s\n" "${found[@]}") result.txt