1

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 ?

Kumar
  • 823
  • 3
  • 20
  • 43

4 Answers4

4

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.

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

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

David Rickman
  • 3,320
  • 18
  • 16
0

Try

#!/bin/sh
variable=`grep "06-02-2010" feb2010`
OR
variable=grep "$(date +%d-+%m-%Y)" feb2010
echo $variable should return the good output
Razique
  • 2,276
  • 1
  • 19
  • 23
0

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

Jim B
  • 24,081
  • 4
  • 36
  • 60