2

I want to grep the current date in a file, but also output the next 5 lines. How do i do that with the grep or anything else. grep -A 5 file.txt does not work and the output is shown below. Please help !

$grep $(date +"%m/%d") file.txt - this works only for the first line. But i want the next 5 lines displayed as well.

$ grep -A 5 '$(date +"%m/%d")' file.txt
grep: Not a recognized flag: A
Usage: grep [-r] [-R] [-H] [-L] [-E|-F] [-c|-l|-q] [-insvxbhwyu] [-p[parasep]] -e pattern_list...
        [-f pattern_file...] [file...]
Usage: grep [-r] [-R] [-H] [-L]  [-E|-F] [-c|-l|-q] [-insvxbhwyu] [-p[parasep]] [-e pattern_list...]
        -f pattern_file... [file...]
Usage: grep [-r] [-R] [-H] [-L] [-E|-F] [-c|-l|-q] [-insvxbhwyu] [-p[parasep]] pattern_list [file...]
  • I can't see an error with your command. Try, `cat file.txt | grep -A 5 '$(date +"%m/%d")' – coteyr Apr 26 '15 at 7:01
  • 1
    Please run grep -V for us. Are you on SunOS/Solaris with its notoriously frugal tools? – Ulrich Schwarz Apr 26 '15 at 7:04
  • I just verified grep -A 5 "$(date +"%b %d")" /var/log/syslog works for me just fine. But as Ulrich suggests it could be a picky version of grep. – coteyr Apr 26 '15 at 7:05
  • I am using AIX. grep -V does not work either. displays $ grep -V grep: Not a recognized flag: V Usage: grep [-r] [-R] [-H] [-L] [-E|-F] [-c|-l|-q] [-insvxbhwyu] [-p[parasep]] -e pattern_list... [-f pattern_file...] [file...] Usage: grep [-r] [-R] [-H] [-L] [-E|-F] [-c|-l|-q] [-insvxbhwyu] [-p[parasep]] [-e pattern_list...] -f pattern_file... [file...] Usage: grep [-r] [-R] [-H] [-L] [-E|-F] [-c|-l|-q] [-insvxbhwyu] [-p[parasep]] pattern_list [file...] – Cecil Daniel Apr 26 '15 at 8:03
5

Your grep doesn't support the -A flag, so you can't use that. But you should be able to get the same result with awk.

awk -v dt=$(date +%m/%d) '$0~dt{counter=5}counter>=0{print;counter--}' file.txt

This sets a counter to 5 when a match is found, and prints and decrements the counter while it's not negative.

  • Awesome. Thank you so much. Works like a charm. :) – Cecil Daniel Apr 26 '15 at 7:19
  • I believe that this prints only the matching line and the next four.  The matching line + the next five = six lines, so you need to set counter=6. – G-Man Apr 26 '15 at 8:57
  • @G-Man: you're right, fixed. – Mat Apr 26 '15 at 9:00
  • correct i changed it to 6 and then works like a charm :) – Cecil Daniel Apr 26 '15 at 10:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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