UNIX grep命令(grep -v grep)

Dhi*_*ash 4 unix grep

我正在经历一些事情并找到了我无法理解的东西,

grep -v grep

这意味着什么?我知道-v开关会选择所有不匹配的行.但为什么第二个grep呢?

这是完整的命令:

ps -ef | grep rsync -avz \
| grep oradata${DAY}_[0-1][0-9] \
| grep -v grep \
| awk '{print $2}' | wc -l
Run Code Online (Sandbox Code Playgroud)

Ami*_*mit 9

grep当用于ps -ef输出时也grep用于过滤输出ps -ef.

grep -v grep表示grep在命令输出中不包含用于过滤的内容.

您还可以grep通过使用regex模式来避免结果.例如,在以下示例中,您不需要在输出中grep -v grep避免grep:

ps -ef | grep [r]sync
Run Code Online (Sandbox Code Playgroud)

这是另一个示例,显示不同的命令及其输出,注意第一个grep也在输出中,而最后两个grep不在输出中打印:

$ ps -ef | grep ipython
  501 18055 18031   0 12:44AM ttys000    0:00.00 /bin/bash /Users/amit/anaconda/bin/python.app /Users/amit/anaconda/bin/ipython notebook --profile=ocean
  501 18056 18055   0 12:44AM ttys000    0:00.85 /Users/amit/anaconda/python.app/Contents/MacOS/python /Users/amit/anaconda/bin/ipython notebook --profile=ocean
  501 18067 18031   0 12:44AM ttys000    0:00.00 grep ipython

$ ps -ef | grep ipython | grep -v grep
  501 18055 18031   0 12:44AM ttys000    0:00.00 /bin/bash /Users/amit/anaconda/bin/python.app /Users/amit/anaconda/bin/ipython notebook --profile=ocean
  501 18056 18055   0 12:44AM ttys000    0:00.85 /Users/amit/anaconda/python.app/Contents/MacOS/python /Users/amit/anaconda/bin/ipython notebook --profile=ocean

$ ps -ef | grep [i]python
  501 18055 18031   0 12:44AM ttys000    0:00.00 /bin/bash /Users/amit/anaconda/bin/python.app /Users/amit/anaconda/bin/ipython notebook --profile=ocean
  501 18056 18055   0 12:44AM ttys000    0:00.85 /Users/amit/anaconda/python.app/Contents/MacOS/python /Users/amit/anaconda/bin/ipython notebook --profile=ocean
Run Code Online (Sandbox Code Playgroud)