2

If I wanted to search for all lines in a file that start with a date, such as "May 1", how would I do that with sed or awk? I need to extract this data and either send to screen or a file. Thanks.

2
  • Is May the only month, or are you looking for any month followed by a date?
    – jasonwryan
    May 5, 2015 at 2:48
  • In this example I need every line that begins with "May 1", but it could be other months.
    – user53029
    May 5, 2015 at 3:02

2 Answers 2

7

To extract lines that start with May 1:

grep "^May 1\b" file

Or:

sed -n '/^May 1\>/p' file

Or:

awk '/^May 1\>/' file

The above two assume a tool, such as the GNU awk or sed, that supports \> as a word boundary regex. The purpose of the word boundary is to prevent the regex from matching, for example, May 10.

More

If you are looking for any day in May:

grep -E "^May [[:digit:]]{1,2}\b" file

If you are looking for any day of any month:

grep -E "^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [[:digit:]]{1,2}\b" file
3
  • Probably safer to use an anchor: /^May [0-9]{1,2}/
    – jasonwryan
    May 5, 2015 at 2:47
  • Yes yes, this would be the easiest route. awk or sed would need some regex statements.
    – Aloha
    May 5, 2015 at 2:49
  • @jasonwryan Yes, some anchoring is good. I was reading it that he wanted May 1 but I see that you have asked for clarification.
    – John1024
    May 5, 2015 at 2:54
0
printf %s\\n 'Apr 30 aaa' \
             'May 1 bbb' \
             'Feb 29 ccc' \
             'Feb 30 ddd' |

sed -n '/^\(Apr\|Jun\|Sep\|Nov\) \([1-9]\|[12][0-9]\|30\)\>/p
        /^\(Jan\|Mar\|Jul\|Aug\|May\|Oct\|Dec\) \([1-9]\|[12][0-9]\|3[01]\)\>/p
        /^\(Feb\) \([1-9]\|[12][0-9]\)\>/p'

Output:

Apr 30 aaa
May 1 bbb
Feb 29 ccc

You must log in to answer this question.

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