Grep:搜索较短的文件路径,忽略较长的文件路径

  • 本文关键字:文件 路径 Grep 搜索 path grep
  • 更新时间 :
  • 英文 :


我有一个自动化脚本,用于查看/etc/mtab。在下面的示例中,我想使用grep来查找字符串nfs.example.org:/directory/subdirectory1,但忽略字符串nfs.example.org:/directory/subdirectory1/subdirectory2:

nfs.example.org:/directory/subdirectory1
nfs.example.org:/directory/subdirectory1/subdirectory2

不幸的是,--word-regexp并没有像我预期的那样工作:

% grep --word-regexp /directory/subdirectory1 /etc/mtab
nfs.example.org:/directory/subdirectory1/subdirectory2 /directory/subdirectory1/subdirectory2 ...
nfs.example.org:/directory/subdirectory1 /directory/subdirectory1 ...

我认为--word-regexp会检测到第一个,但不会检测到第二个,因为它应该只匹配整个单词:

-w, --word-regexp
Select  only  those  lines  containing  matches that form whole words.  The test is that the matching substring must either be at the beginning of the
line, or preceded by a non-word constituent character.  Similarly, it must be either at the end of the line or  followed  by  a  non-word  constituent
character.  Word-constituent characters are letters, digits, and the underscore.

我还可以尝试什么来匹配短路径而不是长路径?

感谢@Cyrus为我指明了正确的方向。我不得不使用一系列引号和空格来匹配。我实际上是在for循环中通过并行SSH脚本调用这个命令,这意味着空白&报价有点复杂。

以下对我有效:

for MNT in "/directory/subdirectory1 " /directory/subdirectory1/subdirectory2
do
pssh hosta hostb hostc -c "grep -w '$MNT' /etc/mtab"
done

最新更新