grep 带有字符串变量和正则表达式
我正在尝试匹配一个正则表达式,其字符串部分包含在变量中,如下所示:
matches=`grep "^"$*"[ ][0-9]\{1,\}" --count phonelist.txt`
其中正则表达式表示“phonelist.txt 中以命令行参数开头的任何行,后跟空格和具有任意多位数字的数字” 。尝试了很多东西但似乎无法得到它。 帮助
I am trying to match a regular expression whose string part is contained in a variable as in :
matches=`grep "^"$*"[ ][0-9]\{1,\}" --count phonelist.txt`
where the regex would mean "any line in phonelist.txt which starts with the command line arguments followed by a space and a number with arbitrary many digits". Have tried many things but can't seem to get it.
Help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您想将每个命令行参数视为单独的模式(即,如果一行以任何命令行参数开头,则您需要“匹配”),那么您可以构建整个扩展正则表达式,例如this:
您可以使用 set IFS to
|
并使用$*
自动将位置参数扩展为该形式,如下所示:括号形成子 shell,以便更改后的 IFS仅限于括号中的命令(您可能不希望该设置影响脚本的后续部分。
在使用包含扩展正则表达式元字符的命令行参数时需要小心。例如,如果您想搜索文字字符串
foo(bar)
,您需要传递类似foo\(bar\)
的内容作为参数(与文字字符串匹配的 ERE),您可以在实际命令行上写为'foo\(bar\)'
。最后,将其放回到原始命令中并告诉
grep
期望扩展正则表达式 (< code>-E):命令替换
$()
实际上是它自己的子 shell,因此修改后的 IFS 值不会“逃逸”到脚本的后续部分。If you want to treat each command line argument as a separate pattern (i.e. you want a “match” if a line starts with any of command line arguments), then you might construct your whole extended regular expression like this:
You can use set IFS to
|
and use$*
to automatically expand your positional parameters into that form like this:The parentheses form a subshell so that the changed IFS is limited to the commands in the parentheses (you may not want that setting to affect later parts of the script.
You will need to be careful when using command line arguments that contain extended regular expression metacharacters. For example, if you wanted to search for the literal string
foo(bar)
, you would need to pass something likefoo\(bar\)
as the argument (an ERE that matches the literal string), which you might write as'foo\(bar\)'
on an actual command line.Finally, put it back into your original command and tell
grep
to expect an extended regular expression (-E
):The command substitution
$()
is effectively its own subshell, so the modified IFS value will not “escape” into later parts of the script.尝试一下:
Give this a try:
我认为你应该尝试:
bash的手册页说:
$*
“扩展为一个单词,每个参数的值由IFS
特殊变量的第一个字符分隔”而对于$@
来说,“每个参数都会扩展为一个单独的单词。也就是说,“$@
”相当于“$1”“$2”...”。在正则表达式中,您需要将所有参数连接到一个单词中。
I think you should try:
bash's man page says:
$*
"expands to a single word with the value of each parameter separated by the first character of theIFS
special variable" whereas with$@
"each parameter expands to a separate word. That is, "$@
" is equivalent to "$1" "$2" ...".In your regular expression you will need all the arguments joined into one single word.