How to put a string search with grep command into if statement?
Another option:
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
Try this:
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
grep
can search for patterns in multiple files, so no need to use an OR/NOT operator.
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
Note: ((n++))
is a ksh extension (also supported by zsh
and bash
). In POSIX sh
syntax, you'd need n=$((n + 1))
instead.