Yuri Burkov
Yuri Burkov

Reputation: 141

Bash how to find a pattern after a pattern

So I am trying to find a pattern after specific pattern

For example the input file would be

/wav1/af_ZA_IT_001_B.wav;2.98;3.67;;;dáár wav1
/wav1/af_ZA_IT_001_B.wav;2.98;3.67;;;dáár we1
/wav1/af_ZA_IT_001_B.wav;4.05;7.9;;;dit is franko wav1 van niekerk hier en kobus buys kobus

Then the output file would look for wav1 after ;;;

with using

grep "wav1" file.txt

I get all wav1 highlighted.

/wav1/af_ZA_IT_001_B.wav;2.98;3.67;;;dáár wav1
/wav1/af_ZA_IT_001_B.wav;2.98;3.67;;;dáár we1
/wav1/af_ZA_IT_001_B.wav;4.05;7.9;;;dit is franko wav1 van niekerk hier en kobus buys kobus

However since every file starts with wav1 I cannot find where wav1 is located after ;;;.

How do I find a pattern ('wav`') after a pattern (';;;')

Expected output would be

/wav1/af_ZA_IT_001_B.wav;2.98;3.67;;;dáár wav1
/wav1/af_ZA_IT_001_B.wav;4.05;7.9;;;dit is franko wav1 van niekerk hier en kobus buys kobus

Upvotes: 2

Views: 91

Answers (3)

Ryszard Czech
Ryszard Czech

Reputation: 18641

With GNU grep, match ;;;, then any text with .* and then match wav1 using \bwav1\b to make sure you do not match wav12:

grep -P ';;;.*\bwav1\b' yourfile.txt

P option means PCRE engine will be used.

Upvotes: 3

tripleee
tripleee

Reputation: 189948

Easily with grep;

grep ';;;.*wav' file.txt

If you have grep -P you can use fancy Perl regex tricks; the following will only highlight the actual wav match:

grep -P ';;;.*\Kwav' file.txt

If you want to extract only the part after ;;; you can use sed;

sed -n 's/.*;;;//;/wav/p' file.txt

Single quotes are generally preferable around regular expressions to avoid having the shell mess with the regex (double quotes are weaker, and won't protect backslashes, backticks, or many dollar signs).

Upvotes: 5

coelhudo
coelhudo

Reputation: 5090

I believe that

grep -e ";;;.*wav.*" yourfile.txt

would suffice.

Upvotes: 2

Related Questions