Linux下不使用任何标志位,通过egrep正则表达式排除文件中指定单词的方法
-v Flag Let's break down where you went wrong first, then fix this up.
Your current command egrep "^[ford]" ./cars.txt doesn’t work because [ford] is a character class—it matches any single character that’s either f, o, r, or d at the start of a line. That’s why it’s only pulling in lines starting with those characters (including the ones with "ford"), which is the exact opposite of what you want.
The Correct Regular Expression
To match lines that do not contain the word "ford" without using the -v flag, you can use a negative lookahead assertion (supported by egrep’s extended regular expressions):
egrep '^(?:(?!ford).)*$' ./cars.txt
How This RegEx Works
Let’s break down each component to make it clear:
^: Anchors the match to the start of the line.(?!ford): A negative lookahead assertion—it checks that the substring "ford" does not appear starting at the current position in the line..: Matches any single character (except a newline).*: Repeats the preceding group (the negative lookahead + any character) zero or more times, covering the entire line.$: Anchors the match to the end of the line.
This ensures every position in the line is checked to confirm "ford" isn’t present, effectively replicating the behavior of egrep -v 'ford' without using the -v flag.
Note for Your Sample cars.txt
If your file has all car entries in one continuous line (like the sample you shared), this command will only output that line if it doesn’t contain "ford". If you need to extract individual car entries that exclude "ford", you’d adjust the regex to account for entry boundaries (e.g., splitting on whitespace groups), but the line-based regex above fits your core goal of excluding any content with "ford".
内容的提问来源于stack exchange,提问作者Jeel Patel

