4

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.

1
  • 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
    Commented Jan 27, 2015 at 9:52

3 Answers 3

6

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.

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

try

cat abc.fil | sed s/yyyymmdd/`date +%Y%m%d`/
5
  • 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). Commented Jan 27, 2015 at 9:38
  • Not from me :-) Commented Jan 27, 2015 at 9:39
  • 1
    It's better to use $(...) instead of backticks. Otherwise, it works.
    – orion
    Commented Jan 27, 2015 at 9:54
  • Why is it better (appart from the need to escape the quotes for this forum)?
    – YoMismo
    Commented Jan 27, 2015 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
    Commented Jan 27, 2015 at 10:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .