Home > Software design >  Using a .sed file and invoking it from a .bash file to find and replace a word with the current date
Using a .sed file and invoking it from a .bash file to find and replace a word with the current date

Time:10-15

I have a .sed, .bash and .txt file

The x.bash file has this within it

#!/bin/bash

./y.sed "$1"

The z.txt file has this within it

<dstamp>

The y.sed file has this command to find and replace <dstamp> with the current date

#!/bin/sed -rf

s/<dstamp>/date ' %Y%m%d'/e

This works. It substitutes <dstamp> with the current date

However, the command doesn't work if there's another word preceding <dstamp> in my z.txt file, for example:

Date: <dstamp>

Running it gives this error:

./x.bash z.txt

sh: 1: Date:: not found

I'm assuming that what it's missing is the "/g" at the end of s///g. So, how could I also make this global? I.e. make "e" and "g" work together?

Additionally, anytime I modify this, as such

s/<dstamp>/date ' %Y%m%d'/e

s/<dstamp>/New date: date ' %Y%m%d'/e

It also prompts me with the same error:

sh: 1: Date:: not found

Technically two questions being asked, but any help is welcome.

CodePudding user response:

e executes the entire line. You need to do it like this:

#!/bin/sed -f
s/'/'\\''/g
s/%/%%/g
s/\(.*\)<dstamp>\(.*\)/date  '\1%Y%m%d\2'/e

It'd be far easier this way though:

sed "s/<dstamp>/$(date  %Y%m%d)/" z.txt
  • Related