0

I have an expression of the form @(<date calculation>) that I want to replace with the result of date +%s --date "now<date calculation>". So for example @(-1 day) would be replaced with the result of date +%s --date "now -1 day".

The expression is embedded in a line of text and I can have several. For example echo hi @(-1 day) bye "@(-1 hour)". The result of evaluation should be something like echo hi 1491848561 bye "1491931365". So I want just the expression to be evaluated, but nothing else.

I tried using GNU's sed 'e' command: sed -r 's|@\(([^)]*)\)|date +%s --date "now\1"|e', but this evaluates the entire line, not just the replaced expression.

I'm not attached to using sed, so any other suggestion is welcome, but I'm curious on how to make sed work, for general knowledge

2
  • Please edit your question and show us your actual input file. Your issue is that sed is taking the whole line. How can we help solve that if you don't show what the line is?
    – terdon
    Apr 11 '17 at 19:19
  • i gave a 'For example'. The file is just a text file.
    – IttayD
    Apr 12 '17 at 4:12
2

As far as I know, the GNU sed e modifier always passes the whole pattern space to the shell - and that shell is always /bin/sh

You may have more luck using perl - for example

$ echo 'For example echo hi @(-1 day) bye "@(-1 hour)"' | 
    perl -pe 's/@\((.*?)\)/sprintf "%s", $d = `date +%s --date "now $1"`, chomp $d/ge'
For example echo hi 1491874845 bye "1491957645"

(unlike sed, the perl e modifier appears not to remove the trailing newline from the shell command's output - hence the chomp).

However if you are going to use perl it is likely preferable to make use of one of the available modules to do the date manipulation - for example

$ echo 'For example echo hi @(-1 day) bye "@(-1 hour)"' | 
    perl -MDate::Manip=ParseDateDelta,UnixDate -pe 's/@\((.*?)\)/UnixDate(ParseDateDelta($1), "%s")/ge'
For example echo hi 1491875065 bye "1491957865"

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.