在 grep 中使用星号 [英] Using the star sign in grep
问题描述
我正在尝试在 linux/bash 的特定文件中搜索子字符串abc"
I am trying to search for the substring "abc" in a specific file in linux/bash
所以我这样做:
grep '*abc*' myFile
它什么都不返回.
但如果我这样做:
grep 'abc' myFile
它正确返回匹配项.
现在,这对我来说不是问题.但是如果我想 grep 一个更复杂的字符串怎么办,比如
Now, this is not a problem for me. But what if I want to grep for a more complex string, say
*abc * def *
我将如何使用 grep 完成它?
How would I accomplish it using grep?
推荐答案
星号只是一个重复运算符,但你需要告诉它你重复了什么./*abc*/
匹配包含 ab 和零个或多个 c 的字符串(因为第二个 * 在 c 上;第一个没有意义,因为它没有任何重复).如果你想匹配任何东西,你需要说 .*
-- 点表示任何字符 (在某些指导方针内).如果你只想匹配 abc,你可以说 grep 'abc' myFile
.对于更复杂的匹配,您需要使用 .*
-- grep 'abc.*def' myFile
将匹配包含 abc 后跟 def 的字符串以及可选的内容之间.
The asterisk is just a repetition operator, but you need to tell it what you repeat. /*abc*/
matches a string containing ab and zero or more c's (because the second * is on the c; the first is meaningless because there's nothing for it to repeat). If you want to match anything, you need to say .*
-- the dot means any character (within certain guidelines). If you want to just match abc, you could just say grep 'abc' myFile
. For your more complex match, you need to use .*
-- grep 'abc.*def' myFile
will match a string that contains abc followed by def with something optionally in between.
根据评论更新:
*
与控制台中的 * 并不完全相同.在控制台中,* 是 glob 结构 的一部分,仅用作通配符(例如 ls *.log
将列出所有以 .log 结尾的文件).但是,在正则表达式中,* 是一个修饰符,这意味着它只适用于它前面的字符或组.如果想让正则表达式中的 * 充当通配符,则需要使用前面提到的 .*
-- 点是通配符,星号在修改点时表示找到一个或更多点;IE.找到一个或多个任意字符.
*
in a regular expression is not exactly the same as * in the console. In the console, * is part of a glob construct, and just acts as a wildcard (for instance ls *.log
will list all files that end in .log). However, in regular expressions, * is a modifier, meaning that it only applies to the character or group preceding it. If you want * in regular expressions to act as a wildcard, you need to use .*
as previously mentioned -- the dot is a wildcard character, and the star, when modifying the dot, means find one or more dot; ie. find one or more of any character.
这篇关于在 grep 中使用星号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!