How can i grep a nearer word from a file ?

E.g

04-02-2010  Workingday
05-02-2010  Workingday
06-02-2010  Workingday
07-02-2010  Holiday
08-02-2010  Workingday
09-02-2010  Workingday

I stored above data in a file 'feb2010',

By this commend i stored date in one variable date=date '+%d-%m-%Y'

if date is 06-02-2010 , i want to grep "06-02-2010" with Workingday

and want to store the string "Workingday" in a variable

  • How can i do this ?

  • Is there any other option ?

link|improve this question

Crossposted here: stackoverflow.com/questions/2176261/… – Dennis Williamson Feb 1 '10 at 12:14
feedback

4 Answers

up vote 4 down vote accepted

Do you mean something like that?

DATE=$(date '+%d-%m-%Y')
DAY=$(grep $DATE feb2010 | awk '{ print $2 }')
echo $DAY

This greps for your $DATE and selects the second column for the output via awk and stores this output in the variable $DAY.

link|improve this answer
I've posted answers with backticks and been downvoted for it, but nothing wrong with it, I say. – pavium Feb 1 '10 at 11:35
3  
you should use $( ) instead. Not all keyboard layouts have them -- in fact, they are deprecated for portability. See unix.derkeiler.com/Newsgroups/comp.unix.shell/2008-04/… – lorenzog Feb 1 '10 at 11:59
Thanks for the hint. I'm used to them for historical reasons. I will get rid of them. ;-) – christianwolff Feb 1 '10 at 12:49
huh, thanks for the heads up... crazy considering my phone has backticks on the hardware keyboard.... – MidnighToker Feb 1 '10 at 13:17
Why feed grep into awk? DAY=$(awk "/$DATE/"\ '{ print $2 }' feb2010) – mpez0 Feb 1 '10 at 14:36
feedback

month = " 06-02-2010 Workingday " && grep search-string $month

link|improve this answer
feedback

Try

#!/bin/sh
variable=`grep "06-02-2010" feb2010`
OR
variable=grep "$(date +%d-+%m-%Y)" feb2010
echo $variable should return the good output
link|improve this answer
feedback

This question doesn't post an OS so here's how you would do this under windows powershell:

((select-string -path .\grepme.txt -pattern (get-date -uformat "%m-%d-%Y")).line).split(' ')[2]

Select-string is grep's equivalent

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.