Bash grep 命令以开头或结尾

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23290926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:17:57  来源:igfitidea点击:

Bash grep command starts with or ends with

bashunixterminalgrep

提问by Daniel Del Core

I'm after a command that will return results based on a pattern match that starts with or ends with a the given pattern.

我正在执行一个命令,该命令将根据以给定模式开头或结尾的模式匹配返回结果。

This is what i have so far.

这是我到目前为止。

"cat input.txt | grep "^in|in$"

My main problem is that i cant get the (or) to work but i can get them to work individually.

我的主要问题是我无法让(或)工作,但我可以让他们单独工作。

Thanks for your help in advance.

提前感谢您的帮助。

回答by Kent

try this:

尝试这个:

grep "^in\|in$" input.txt

by default, grep use BRE, you have to escape the |. Or use grep's -E or -P, in order to avoid escaping those char with special meaning.

默认情况下,grep 使用BRE,您必须转义|. 或者使用 grep's -E or -P,以避免转义那些具有特殊含义的字符。

P.S, the catis no necessary.

PS,cat没必要。

回答by Jotne

This awkshould work:

awk应该有效:

awk '/^start|end$/' file

It will print all lines starting with startor ending with end

它将打印以开头start或结尾的所有行end

cat file
nothing
start with this
or it does have an end
or the end is near

awk '/^start|end$/' file
start with this
or it does have an end

回答by Galzzly

Have you thought of using egrep rather than grep? Using the following should work for what you're after:

你有没有想过使用 egrep 而不是 grep ?使用以下内容应该适用于您所追求的内容:

egrep "^in|in$" input.txt

There's no need to have the cat at the start, the above will work fine.

不需要一开始就养猫,上面的就可以了。