Reputation: 1431
I have a set of files where I want to put something like ${today+N} and replace those with 'YYYY-MM-DD'. For example, if I see "some date: ${today+5} I want that to end up being "some date: 2019-11-27'.
I thought I could do this:
echo "my test: \${today+54}"| gsed -e "s/\${today+\([0-9]*\)}/$(date -v +\1d '+%Y-%m-%d')/g"
This acts like date -v +1d and doesn't do what I want, which would be date -v +54d.
The regex isn't the problem--The backreference works as I want it to, as demonstrated by:
echo "mat test \${today+54}"| gsed -e "s/\${today+\([0-9]*\)}/\1/g"
How do I pass the backreference to the subcommand?
Upvotes: 1
Views: 332
Reputation: 203368
Here's one way to do what you want using GNU awk for the 3rd arg to match():
$ cat tst.awk
{
while ( match($0,/(.*)\${([^}]+)([+-][0-9]+)}(.*)/,a) ) {
cmd = "date -d \047" a[2] " " a[3] " days\047 +\047%F\047"
newDate = ( (cmd | getline line) > 0 ? line : "N/A" )
$0 = a[1] newDate a[4]
}
print
}
$ cat file
some date: ${today+5}, some other date: ${yesterday-30}
$ awk -f tst.awk file
some date: 2019-11-28, some other date: 2019-10-23
I have GNU date which doesn't have a -v
option so just massage the date
command string to suit for your system.
It's easily tweaked to work for any awk or depending on what you want those date commands in your input file to look like you could eliminate the calls to date
and call gawk time functions instead for much faster execution. There's lots of other ways you could do things to give you more flexibility on what those data commands contain as well but with just 1 sample of the input it's not worth trying to guess what else you might want to be able to do.
Upvotes: 2
Reputation: 42458
You can do this using GNU sed's e
command:
echo "my test: \${today+54}" \
| gsed -e "s/\${today+\([0-9]*\)}/\$(date -v '+\1d' '+%Y-%m-%d')/g;s/.*/echo &/;e"
Firstly you replace all matches of your token with a subprocess command:
echo "my test: \${today+54}" \
| gsed -e "s/\${today+\([0-9]*\)}/\$(date -v '+\1d' '+%Y-%m-%d')/g"
my test: $(date -v '+54d' '+%Y-%m-%d')
Then, you stick an echo
on the front and run it through the e
command.
However, depending on the rest of your message, you may run into issues treating the contents as a shell command.
More info: https://www.gnu.org/software/sed/manual/sed.html#Extended-Commands
Upvotes: 1