Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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 ?

share|improve this question
    
Crossposted here: stackoverflow.com/questions/2176261/… –  Dennis Williamson Feb 1 '10 at 12:14

4 Answers 4

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.

share|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. ;-) –  cwo Feb 1 '10 at 12:49
    
huh, thanks for the heads up... crazy considering my phone has backticks on the hardware keyboard.... –  BuildTheRobots Feb 1 '10 at 13:17
    
Why feed grep into awk? DAY=$(awk "/$DATE/"\ '{ print $2 }' feb2010) –  mpez0 Feb 1 '10 at 14:36

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

share|improve this answer

Try

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

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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