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

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

  • 2
    It doesn't have much to do with cat. Actually, nothing at all. You just want to replace a pattern with a current date. – orion Jan 27 '15 at 9:52

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.


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.

| improve this answer | |
  • Why do you have so many {1}s? They do absolutely nothing. – Doorknob Jan 27 '15 at 13:40
  • @Doorknob I see, they are not necessary, I updated my answer, thanks – chaos Jan 27 '15 at 13:44
> today=$(date +%Y%m%d)
> sed "s/yyyymmdd/${today}/g" abc.fil
o/p: 20150127.xyz.doc
| improve this answer | |


cat abc.fil | sed s/yyyymmdd/`date +%Y%m%d`/
| improve this answer | |
  • 3
    Why the downvote? That command will work in csh/tcsh and in Bourne-like shells provided $IFS doesn't contain digits (cat is redundant though). – Stéphane Chazelas Jan 27 '15 at 9:38
  • Not from me :-) – Hauke Laging Jan 27 '15 at 9:39
  • 1
    It's better to use $(...) instead of backticks. Otherwise, it works. – orion Jan 27 '15 at 9:54
  • Why is it better (appart from the need to escape the quotes for this forum)? – YoMismo Jan 27 '15 at 10:09
  • I'll answer my question myself. It isn't better, it only makes a difference which is that the quotes retain the meaning of the backslash while $() does not treat it specially. tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_04.html – YoMismo Jan 27 '15 at 10:26

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.