Using sed, how to print all lines that match a certain date?

0

Using sed, how to print all lines where the birthdays are in November or December?

Assuming input file name "datebook" as follows:

Steve Blenheim:238-923-7366:95 Latham Lane, Easton, PA 83755:11/12/56:20300
Betty Boop:245-836-8357:635 Cutesy Lane, Hollywood, CA 91464:6/23/23:14500
Igor Chevsky:385-375-8395:3567 Populus Place, Caldwell, NJ 23875:6/18/68:23400
Karen Evich:284-758-2857:23 Edgecliff Place, Lincoln, NB 92743:7/25/53:85100
Fred Fardbarkle:674-843-1385:20 Parak Lane, Duluth, MN 23850:4/12/23:780900
Lori Gortz:327-832-5728:3465 Mirlo Street, Peabody, MA 34756:10/2/65:35200
Paco Gutierrez:835-365-1284:454 Easy Street, Decatur, IL 75732:2/28/53:123500
Ephram Hardy:293-259-5395:235 CarltonLane, Joliet, IL 73858:8/12/20:56700
ABE LINCOLN:813-555-0123:1549 Cabin Drive, Springfield, IL 61801:2/12/09:79000
James Ikeda:834-938-8376:23445 Aster Ave., Allentown, NJ 83745:12/1/38:45000

Steve

Posted 2012-10-04T17:11:23.327

Reputation: 287

Are the dates in M/D/Y or D/M/Y format? – user1686 – 2012-10-04T17:16:04.910

Answers

5

egrep '^[^:]*:[^:]*:[^:]*:(11|12)/'
sed -rn '/^[^:]*:[^:]*:[^:]*:(11|12)\//p'
  • /regex/p – print lines matching a regex
  • ^ – beginning of line
  • [^:]+ – first, second, third fields (any number of any characters except :)
  • : – field separators
  • (11|12)\/ – either 11 or 12, followed by a /
awk -F: '$4 ~ /^(11|12)\//'
perl -aF: -ne 'print if $F[3] =~ /^(11|12)\//'

user1686

Posted 2012-10-04T17:11:23.327

Reputation: 283 655

1Could you please explain the sed command in details? how come we have so many [^:]+ ? Thank you – Steve – 2012-10-04T17:35:41.550

Could you please read a regexp tutorial? [], ^, * are explained in many places. thank you

– user1686 – 2012-10-04T17:41:59.627

1Could have done shorter? I'd have written ^([^:]+:){3}(11|12), or even (looking at the format) :(11|12)\/. – m4573r – 2012-10-04T17:48:49.127

1or, anchor at the end: /:1[12][^:]*:[^:]*$/ – glenn jackman – 2012-10-04T23:15:33.973

1Your side-by-side comparison demonstrates the advantages of a language that knows what a field is (awk and perl) versus ones that just see streams of characters (egrep and sed). – Isaac Rabinovitch – 2012-10-05T05:41:53.103

sed -rn '/^[^:]:[^:]:[^:]*:(11|12)//p' => this works as expected. thank you Grawity – Steve – 2012-10-05T07:15:13.603

1

Not sed, but grep is easier and more appropriate.

grep -E "(11|12)/\d{1,2}/\d{1,2}" steve.txt

(11|12) means match either 11 or 12 and \d{1,2} means match 1 or 2 digits.

colons

Posted 2012-10-04T17:11:23.327

Reputation: 196