Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

grep

awk

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 
like image 460
goose goose Avatar asked Aug 31 '25 10:08

goose goose


1 Answers

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
like image 188
John1024 Avatar answered Sep 04 '25 05:09

John1024