简体   繁体   中英

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' .

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM