简体   繁体   English

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

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

I am working in a bash shell and I am trying to print only the line of the first occurrence of the string. 我在一个bash shell中工作,我试图只打印第一次出现的字符串的行。 For example, for the string ' auir ', if I have the file myfile.txt and it contains: 例如,对于字符串' 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? 我怎样才能获得' auir '出现的第一行? It'd be great if it was just a single command or pipeline of commands. 如果它只是一个命令或命令管道,那就太棒了。

Any insight is greatly appreciated. 非常感谢任何见解。

用这个:

grep -m1 auir myfile.txt

This sed command 这个sed命令

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

solves your problem. 解决你的问题。

This might work for you: 这可能对你有用:

sed '/auir/!d;q' file

or 要么

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

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

或者它可以像这样简单

grep auir myFile.txt|head -1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM