bash UNIX:使用 egrep 或 sed 查找第一次出现字符串的行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10676199/
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 02:20:13  来源:igfitidea点击:

UNIX: Using egrep or sed to find the line with the first occurrence of a string?

bashunixsed

提问by tf.rz

I am working in a bash shell and I am trying to print only the line of the first occurrence of the string. For example, for the string 'auir', if I have the file myfile.txt and it contains:

我在 bash shell 中工作,我试图只打印字符串第一次出现的行。例如,对于字符串 ' auir',如果我有文件 myfile.txt 并且它包含:

123
asdf
4wirajw
forauir somethingelse
starcraft
mylifeforauir
auir
something else
tf.rzauir

I want to output "forauir somethingelse"

我想输出“ forauir somethingelse

So far, I use the command

到目前为止,我使用命令

sed -n '/auir/p' myfile.txt

which gives me all the occurrences of this string. How can I only get the first line that 'auir' occurs on? It'd be great if it was just a single command or pipeline of commands.

这给了我这个字符串的所有出现。我怎样才能只得到“ auir”出现的第一行?如果它只是一个命令或命令管道,那就太好了。

Any insight is greatly appreciated.

任何见解都非常感谢。

采纳答案by beerbajay

This sedcommand

这个sed命令

sed -n '/auir/p' myfile.txt | head -1

sed -n '/auir/p' myfile.txt | head -1

solves your problem.

解决你的问题。

回答by the paul

Use this:

用这个:

grep -m1 auir myfile.txt

回答by potong

This might work for you:

这可能对你有用:

sed '/auir/!d;q' file

or

或者

sed -n '/auir/{p;q}' file

回答by loganaayahee

sed -n -e '4s/auir/auir/p' file

sed -n -e '4s/auir/auir/p' 文件

回答by mawia

Or it can be as simple as this

或者它可以像这样简单

grep auir myFile.txt|head -1