goose goose
goose goose

Reputation: 96

Find first occurrence of a string after the first occurrence of another string with bash

I have an input file that looks like this and i want the first occurrence of words but only after the first occurrence of special

The numbers are only there so i know i got the right string

EDIT: I realized that it matters the strings have /'s

words/and/stuff #1
words/more #2
some/other/words #3
special/this #1
words/i/need/you/i.really.need.you #4
special/cool #2 
words/random #5

Im trying to find the first occurrence of "word" after i find the first occurrence of "special"

The output should be

words/i/need/you/i.really.need.you #4

Ive tried the following

grep -m1 special file | grep -m1 words file 

awk 'NR==1,/special/ && NR==1,/words/ {print $0}' file 

Upvotes: 4

Views: 5410

Answers (2)

John1024
John1024

Reputation: 113814

Try:

$ awk '/special/{f=1} f && /words/ {print; exit}' file 
words/i/need/you/i.really.need.you #4

How it works:

  • /special/{f=1}

    If the current line matches special then set variable f to 1

  • f && /words/ {print; exit}

    If f is non-zero and the current line matches words, then print the current line and exit.

Words with slashes

If the word you want to match is not merely surrounded by slashes but includes them, the same code works. It is just necessary to escape the slashes. For example, if we are looking for the word words/i/need after special:

$ awk '/special/{f=1} f && /words\/i\/need/ {print; exit}' file 
words/i/need/you/i.really.need.you #4

Upvotes: 4

RavinderSingh13
RavinderSingh13

Reputation: 133428

Could you please try following.

awk '
$0=="words"{
  count++
  if(special_count==1){
    print "String words count is: "count
    exit
  }
}
/special/{
  special_count++
}
'  Input_file

Upvotes: 0

Related Questions