Sal
Sal

Reputation: 705

Find text files in bash

I have a bunch of email's as text files in multiple directories under one directory. I am trying to write a script where I would type in a date as 3 separate command line arguments like so:

findemail 2015 20 04 

the format being yyyy/dd/mm and it would bring up all filenames for emails that were sent on that day. I am unsure where to start for this though. I figured I could use find possibly but I am new to scripting so I am unsure. Any help would be greatly appreciated!

The timestamp in the email looks like:

TimeStamp: 02/01/2004 at 11:19:02 (still in the same format as the input)

Upvotes: 1

Views: 167

Answers (2)

tripleee
tripleee

Reputation: 189936

grep -lr "$(printf "^TimeStamp: %02i/%02i/%04i" "$2" "$1" "$3")" path/to/directory

The regex looks for mm/dd/yyyy; swap the order of $1 and $2 if you want the more sensible European date order.

The command substitution $(command ...) runs command ... and substitutes its output into the command line which contains the command substitution. So we use a subshell which runs printf to create the regex argument to grep.

The -l option says to list the names of matching files; the -r option says to traverse a set of directories recursively. (If your grep is too pedestrian to have the -r option, it's certainly not hard to concoct a find expression which does the same. See e.g. here.)

Upvotes: 1

TheInnerParty
TheInnerParty

Reputation: 406

The easiest thing to do would be to use a search utility such as grep. Grep has a very useful recursive option that allows searching for a string in all the files in a directory (and subdirectories) that's easy to use.

Assuming you have your timestamp in a variable called timestamp, then this would return a list of filenames that contain the timestamp:

grep -lr $timestamp /Your/Main/Directory/Goes/Here

EDIT: To clarify, this would only search for the exact string, so it needs to be in the exact same format as in the searched text.

Upvotes: 0

Related Questions