我试图grep在包含“ls -l”输出的文件中使用全路径文件名,但是无法正确匹配它。

Shell脚本中的行进行字符串搜索

pcline=`grep -w "$file1" $file2` # grep for file1 in file2 contents

如果我回显命令,则命令的输出如下所示
grep -w run /home/rajesh/rootfs.layout

Expected
lrwxrwxrwx 1 root root 3 Aug 28 run

Actual
lrwxrwxrwx 1 root root 7 Aug 28 bin/run-parts
lrwxrwxrwx 1 root root 3 Aug 28 run
-rwxr-xr-x 1 root root 303 Aug 28 tests/aes/run.sh
-rwxr-xr-x 1 root root 445 Aug 28 tests/auto_ui/run.sh
-rwxr-xr-x 1 root root 320 Aug 28 tests/available_memory/run.sh
-rwxr-xr-x 1 root root 308 Aug 28 tests/fonts/run.sh
-rwxr-xr-x 1 root root 309 Aug 28 tests/html_config_page/run.sh
-rwxr-xr-x 1 root root 361 Aug 28 tests/ipc/run.sh
-rwxr-xr-x 1 root root 304 Aug 28 tests/JSON/run.sh
-rwxr-xr-x 1 root root 303 Aug 28 tests/log4cplus_cpp/run.sh
-rwxr-xr-x 1 root root 301 Aug 28 tests/log4cplus_c/run.sh
-rwxr-xr-x 1 root root 751 Aug 28 tests/msm_basic/run.sh
-rwxr-xr-x 1 root root 472 Aug 28 tests/res_man_dependency/run.sh
-rwxr-xr-x 1 root root 465 Aug 28 tests/res_man_ipc/run.sh
-rwxr-xr-x 1 root root 789 Aug 28 tests/res_man_multi_process/run.sh
-rwxr-xr-x 1 root root 469 Aug 28 tests/res_man_private_client/run.sh
-rwxr-xr-x 1 root root 492 Aug 28 tests/res_man_public_client/run.sh
-rwxr-xr-x 1 root root 311 Aug 28 tests/virt_mem_config/run.sh
lrwxrwxrwx 1 root root 6 Aug 28 var/run]

我尝试的技巧是添加一个空格,这在我的输入文件中得到保证,该空格在控制台中有效,但在将其分配给变量时则无效。
grep " tests/aes/run.sh" /home/rajesh/rootfs.layout

脚本中的行
pcline=`grep \"" $file1"\" $file2`     # grep for file1 in file2 contents

如果我在此脚本中犯了任何错误,请告诉我。

最佳答案

您可以像这样使用egrep:

egrep "(^| )$file1( |$)" "$file2"

如果是file1="run",则上面的命令将匹配字符串run,其后跟行开头或空格,然后是空格或行尾。

关于linux - grep精确词匹配(-w)不适用于文本文件中的文件路径,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18489198/

10-11 06:33
查看更多