Bash script for searching a string

Hi,
I have a file that contains thousands of records. Each record starts with "New Record". I need to search this file based on a given value of "timestamp" and write all the records that match this timestamp into a new file.
I was able to locate the existence of a given value of timestamp using grep, but could not figure out how to extract the record and put it into a file. I am new to scripting and any help will be greatly appreciated.Thanks.
Here is the format of the records in that file:

New Record
//several lines of text
<timestamp>2009-01-14</timestamp>
//several lines of text

New Record
//several lines of text
<timestamp>2009-01-14</timestamp>
//several lines of text

sed -e '/./{H;$!d;}' -e 'x;/timestamp/!d;' yourfile.txt

replace "timestamp" with your timestamp

Thanks funksen. The code you wrote does not extract the entire record. If there is a match in timestamp (i.e. 2009-01-14) then the entire record including the words "New Record" should be copied. In short, if a timestamp matches then copy everything between the tags "New Record" and next "New Record". Thanks.

Are you familiar with output redirection? Use your grep command and just redirect the output using the '>' symbol.

For example:

grep "timestamp" filename > newfile

Thanks Padow, but that gets only the line that contains the "timestamp". I want the entire record to be extracted that contains the given "timestamp". Here is an example, if the file contains this :
New Record
//several lines of text
<timestamp>2009-01-14</timestamp>
//several lines of text

and if I search for 2009-01-04 then my output should be
New Record
//several lines of text
<timestamp>2009-01-14</timestamp>
//several lines of text

If your version of grep supports it, you can use the -p flag which will grab the entire paragraph. If the version you are using does not, try searching your system for other versions of the grep command.

find / -name grep

my code takes the entire paragraph which contains the timestamp, from empty line to empty line, grep -p like padow says is doing the same

the problem is I guess, that the record contains empty lines

unfortunately I don't know how to do this :wink:

Thanks again Padow and funksen. The problem is that a record contains multiple paragraphs and empty lines. I cannot figure out how to use grep -p to get all the paragraphs in a record.

Try this:

$ awk 'BEGIN { RS="New Record" } /timestamp/ { print RS, $0}' filename

agn! It works like a magic :slight_smile: . Thanks a bunch!

No problem. :slight_smile: