Suppose I get the following result after doing a grep "emailed"

/home/John/logs/2013-07-10.171222-0400EDT.html:I have emailed Mark. Thanks

I want to extract the date from this so that my output looks like -

2013-07-10:I have emailed Mark. Thanks

How can I do this using any one of the GNU tools? In particular, I want to pipe the output of grep to the tool. I suppose that sed may be the tool that does this, but I'm not sure how.



$ <grep-command> | sed -r 's|^.*/([0-9]{4}-[0-9]{2}-[0-9]{2})[^:]*:(.*)|\1:\2|'

... ought to work. In detail:

  1. -r tells sed to use extended regular expressions.

  2. s|a(b)c(d)|\1:\2| says "match a then b then c then d, and replace the whole thing with b:d (the first and second parenthesized items, separated by a :", where a .. d are:

    a. ^.*/ - everything (.*) from the beginning of the line (^) to a / character (which is why we're using | instead of / to separate the clauses of the s command).

    b. [0-9]{4}-[0-9]{2}-[0-9]{2} - a digit ([0-9]) four times ({4}), followed by a -, followed by a digit twice, etc.

    c. [^:]*: - anything that isn't a : ([^:]*), followed by a :.

    d. .* - everything else.

  • Wow, that's amazing. Could you please explain what your above command is doing?
    – CodeBlue
    Jul 23 '13 at 21:05
  • Or better yet sed -n -r '/emailed/s/|...|p to get rid of the grep altogether.
    – tripleee
    Jul 24 '13 at 5:21

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.