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 ?

1

4 Answers 4

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.

5
  • I've posted answers with backticks and been downvoted for it, but nothing wrong with it, I say.
    – pavium
    Commented Feb 1, 2010 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
    Commented Feb 1, 2010 at 11:59
  • Thanks for the hint. I'm used to them for historical reasons. I will get rid of them. ;-)
    – chrw
    Commented Feb 1, 2010 at 12:49
  • huh, thanks for the heads up... crazy considering my phone has backticks on the hardware keyboard.... Commented Feb 1, 2010 at 13:17
  • 1
    Why feed grep into awk? DAY=$(awk "/$DATE/"\ '{ print $2 }' feb2010)
    – mpez0
    Commented Feb 1, 2010 at 14:36
0

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

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
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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .