如何将带有grep命令的字符串搜索放入if语句中?

Mre*_*yes 11 grep ksh awk text-processing

我想在两个文件中搜索多个字符串。如果在两个文件中都找到一个字符串,则做一些事情。如果只在一个文件中找到一个字符串,那么做另一件事。

我的命令是下一个:

####This is for the affirmative sentence in both files
if grep -qw "$users" "$file1" && grep -qw "$users" "$file2"; then

####This is for the affirmative sentence in only one file, and negative for the other one
if grep -qw "$users" "$file1" ! grep -qw "$users" "$file2"; then
Run Code Online (Sandbox Code Playgroud)

否定和肯定这些陈述的方式是否正确?pd 我正在使用 KSH 外壳。

先感谢您。

gle*_*man 13

另外一个选项:

grep -qw -- "$users" "$file1"; in_file1=$?
grep -qw -- "$users" "$file2"; in_file2=$?

case "${in_file1},${in_file2}" in
    0,0) echo found in both files ;;
    0,*) echo only in file1 ;;
    *,0) echo only in file2 ;;
      *) echo in neither file ;;
esac
Run Code Online (Sandbox Code Playgroud)


Siv*_*iva 11

尝试这个:

if grep -wq -- "$user" "$file1" && grep -wq -- "$user" "$file2" ; then
   echo "string avail in both files"
elif grep -wq -- "$user" "$file1" "$file2"; then
   echo "string avail in only one file"
fi
Run Code Online (Sandbox Code Playgroud)
  • grep 可以在多个文件中搜索模式,因此无需使用 OR/NOT 运算符。

  • 为什么变量扩展没有引号? (3认同)
  • 不,它们都为 grep 提供了 -q 和 -w 选项。 (2认同)

Luc*_*ini 7

n=0

#Or if you have more files to check, you can put your while here. 
grep -qw -- "$users" "$file1" && ((n++))
grep -qw -- "$users" "$file2" && ((n++))

case $n in 
   1) 
       echo "Only one file with the string"
    ;;
   2)
       echo "The two files are with the string"
   ;;
   0)
       echo "No one file with the string"
   ;;
   *)
       echo "Strange..."
   ;;
esac 
Run Code Online (Sandbox Code Playgroud)

注意:((n++))是 ksh 扩展(也支持zshbash)。在 POSIXsh语法中,您需要n=$((n + 1))改为。