Text-Processing

如何將使用 grep 命令的字元串搜尋放入 if 語句中?

  • August 24, 2018

我想在兩個文件中搜尋多個字元串。如果在兩個文件中都找到一個字元串,那麼做一些事情。如果僅在一個文件中找到一個字元串,則製作另一件事。

我的命令是下一個:

####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

否認和肯定陳述的正確方式嗎?pd 我正在使用 KSH 外殼。

先感謝您。

試試這個:

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 可以在多個文件中搜尋模式,因此無需使用 OR/NOT 運算符。

另外一個選項:

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

引用自:https://unix.stackexchange.com/questions/464475