Replace date with current date

datetext processing

I have a file abc.fil whose content is in the format yyyymmdd.xyz.doc. I want to cat that file abc.fil such that I get the output as 20150127.xyz.doc. Can any one please help me to resolve this problem.

Sample file:

$ cat abc.fil
o/p: yyyymmdd.xyz.doc
yyyymmdd.mno.dat
abc.txt

Output expected: Instead of yyyymmdd I want the current date to be displayed in the same order.

Best Answer

You could use sed:

sed "s/yyyymmdd/$(date '+%Y%m%d')/g" abc.fil

That replaces the string yyyymmdd with the current date formatted as desired.

Edit:

If yyyymmdd is just the format of the date you want to replace, then use that command (assumes GNU sed):

sed -r "s/[12][0-9]{3}[01][0-9][0-3][0-9]/$(date '+%Y%m%d')/g" abc.fil

The long regular expression pattern means the following: The first digit can be 1 or 2 ([12]), the next three can be everything from 0 to 9 ([0-9]), that's the year. Now the month: the first digit can be 0 or 1 and the second can be everything from 0 to 9 ([01][0-9]). And at last the same with the day.

Related Question