【发布时间】:2020-09-28 19:30:13
【问题描述】:
我尝试使用以下代码使 grep 搜索 \2 但是 grep 无法在测试文件中找到匹配的字符串。我正在运行 cygwin。
C:\test 19# val="C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise"
C:\test 20# escval="$(echo "$value" | sed -r 's,\\,\\\\,g')"
C:\test 20# echo $escval
C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Enterprise
C:\test 21# echo "export DIR=\"${val}\"" > testdata
C:\test 22# cat testdata
export DIR="C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise"
C:\test 23# cat testdata | grep -E "^[[:space:]]*export[[:space:]]+${key}=\"${val}\""; echo $?
grep: Invalid back reference
2
C:\test 24# cat testdata | grep -E "^[[:space:]]*export[[:space:]]+${key}=\"${escval}\""; echo $?
1
C:\test 25# grep -V
grep (GNU grep) 3.0
Packaged by Cygwin (3.0-2)
Copyright (C) 2017 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by Mike Haertel and others, see <http://git.sv.gnu.org/cgit/grep.git/tree/AUTHORS>.
尝试使用固定字符串不是一个选项,因为实际表达式..
更新:我也尝试了所有转义,并且修改了我的问题。
【问题讨论】:
-
你为什么使用
grep -E作为字符串?-E不是“表达式”,而是“扩展正则表达式”。-e表示“表达式” -
有或没有 E 我有相同的结果......我使用它是因为实际代码也有一些正则表达式......我只是简化了步骤。
-
我看到了 teds 的回答并修改了 grep... -F(固定字符串)不起作用,因为 -E 和 -F 和排他性...至于转义它以某种方式不起作用,如果我使用 -E 选项...没有 -E 它确实有效。
-
我刚刚从实际更新了测试数据...添加了 export e.t.c
-
是的,我需要整行。
标签: bash search grep escaping backreference