1

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)

Sal
  • 625
  • 2
  • 7
  • 11
  • I imagine you use `TimeStamp:` as a placeholder for something which really does occur in regular, standard email. The `Date:` header would be your first choice, but through malice (spammers) or incompetence (spammers and others) this header sometimes ends up containing something else than the date when the message was actually submitted. – tripleee Apr 21 '15 at 05:58

2 Answers2

1
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.)

Community
  • 1
  • 1
tripleee
  • 175,061
  • 34
  • 275
  • 318
0

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.

TheInnerParty
  • 396
  • 2
  • 13
  • Thank you. How would I handle if they inputted 2014 1 1 per say? (Instead of 2014 01 01) – Sal Apr 21 '15 at 00:04
  • The easiest way would be to prompt the user for each part once at a time. So once for the year, once for the month, and once for the day. Then check to make sure the month has two characters in it, like this: lengthofmonthstring=${#monthinputvar}' then if lengthofmonthstring is not 2, ask the user again. This way also makes sure the user types everything in the correct format (i.e. doesn't put the month before the day) – TheInnerParty Apr 21 '15 at 04:56