简体   繁体   中英

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. For example, for the string ' auir ', if I have the file myfile.txt and it contains:

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

I want to output " 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.

Any insight is greatly appreciated.

用这个:

grep -m1 auir myfile.txt

This sed command

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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