Jafet Soto
Jafet Soto

Reputation: 41

Find file that match patterns located in different lines

I'm doing a program that can find a file(s) that match two patterns given by the user (Date and ID), both patterns are located in different lines inside every file. The files are located in different .zip sub folders. My code is not working and I'm trying to use PCRE DOTALL.

File Sample:

    TextTextTextTextText
    TextTextText: [20-MAY-2017]
    TextTextTextTextText
    TextTextTextTextText
    TextTextTextTextText
    TextTextText: [123456]

Code I'm using:

        echo "Set a specific Date [ DD-MM-YYYY ]: "
        read -r Date
        echo -e "Introduce ID: "
        read -r ID
        #Search pattern
        grep -Pzo '(?s)$Date.*\n.*$ID' .

Upvotes: 0

Views: 49

Answers (1)

miken32
miken32

Reputation: 42712

You can't use variables in single quoted strings. Try this out:

#!/bin/bash
read -r -p "Set a specific Date [ DD-MMM-YYYY ]: " searchdate
read -r -p "Introduce ID: " searchid
grep -Pzo "(?s)\[$searchdate\].*\[$searchid\]" sample.txt

Provided your input doesn't have a / character in it, you could also use the simpler awk command:

awk "/$searchdate/,/$searchid/" sample.txt 

Upvotes: 1

Related Questions