12

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.

2
  • 2
    starcraft as example. awesome. Commented Apr 25, 2013 at 15:11
  • Surely you will be looking for "Aiur"? Commented Feb 20, 2014 at 17:47

5 Answers 5

20

Use this:

grep -m1 auir myfile.txt 
Sign up to request clarification or add additional context in comments.

2 Comments

Yeup, grep is alright, beerbjay beat you to it by 2 minutes though, gotta give him the points. Always nice to know multiple ways to do the same thing though. thanks for the response!
The redirection isn't necessary.
10

This sed command

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

solves your problem.

4 Comments

You might as well use a sed script which quits after printing the first occurrence; like sed '/auir/!d;q'
Thanks so much for the quick response! Works! :)
@tripleee Oh that's imaginative, I'm new to shell stuff, gonna try that out. Thanks!
@tripleee's answer is much more clever than mine :(
5

This might work for you:

sed '/auir/!d;q' file 

or

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

Comments

2

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

Comments

1

Or it can be as simple as this

grep auir myFile.txt|head -1 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.