2

I have a file like as follows

myname
_       something
_       something
_       something
myname
_       something
_       something
myname
_       something
and it follows and no standard other than myname word.

Now I want to print the first set of search from myname to till myname found as below.

myname
_       something
_       something
_

I tried using the following but it is not working.

sed -n -e '/myname/,/myname/ p' file

It prints all the sets.

Tried this also but not worked.

sed -n '/myname/,$ p;/myname/q'
Sriharsha Kalluru
  • 1,663
  • 3
  • 21
  • 26

4 Answers4

3

Here is another way with awk:

awk '/myname/{++c}c<2' file

$ cat file
myname
_       something
_       something
_       something
myname
_       something
_       something
myname
_       something

$ awk '/myname/{++c}c<2' file
myname
_       something
_       something
_       something

If you file is too big then:

awk '/myname/{++c}c==2{exit}1' file
jaypal singh
  • 71,025
  • 22
  • 98
  • 142
  • @SriharshaKalluru You're welcome. Make sure you read this [answer](http://stackoverflow.com/questions/18407890/explain-awk-command/18409469#18409469). It contains many valuable gems! – jaypal singh Mar 09 '14 at 03:51
2
awk  '/myname/{if(b) exit; else b=1}1' filename



$ cat temp.txt
myname
_       something
_       something
_       something
myname
_       something
_       something
myname
_       something

$ awk  '/myname/{if(b) exit; else b=1}1' temp.txt
myname
_       something
_       something
_       something
Amit
  • 18,038
  • 6
  • 44
  • 52
1

This might work for you (GNU sed):

sed '/myname/{:a;n;//Q;$!ba}' file

Look for the pattern myname then set up a loop that, prints the current line, quits (but does not print) if the new current line contains the above pattern or loops.

An alternative, using the grep-like option -n:

sed -n '/myname/{:a;p;n;//q;ba}' file
potong
  • 51,370
  • 6
  • 49
  • 80
  • @ potong: this solution looks a good sed option , can you please elaborate how this command is working ? and what does //Q signify in between . – Vicky Jan 25 '17 at 13:42
  • @protong: From what I understand by //Q is an empty search expression with a 'quit' flag. Is it like when you pass an empty search expression it uses the last used search expression ( which is myname in this example ) ? as I used this sed '/myname/{:a;n;/myname/Q;$!ba}' and it also looks to be working the same way. – Vicky Jan 26 '17 at 02:10
  • 1
    @user3369871 [correct](https://www.gnu.org/software/sed/manual/sed.html#Regexp-Addresses) – potong Jan 26 '17 at 11:06
0

Here is a Bash solution.

n=0
while read line; do
    [[ $line == myname ]] && ((n++))
    [ $n -gt 1 ] && break
    echo $line
done < file
John B
  • 3,466
  • 1
  • 14
  • 20