2

I used the following command to replace all dates with another date string in a file using sed.

 time sed -rn 's/\d{4}-\d{2}-\d{2}/2018-03-14/gp' date.txt

date.txt,

(245176,1129,'CLEARED',to_date('1996-09-10','YYYY-MM-DD'),35097600,'Y','Y','N',to_date('1996-09-10','YYYY-MM-DD'),'Y',null,1121,null,null,null,null,1435,null,to_date('1996-09-30','YYYY-MM-DD'),null,-1,35097600,null,1117,to_date('1997-03-25','YYYY-MM-DD'),null,null,null,to_date('1997-03-25','YYYY-MM-DD'),-1,-1,to_date('1997-03-25','YYYY-MM-DD'),-1,1117,null,'ARRERGW',null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,204,null,null,null,null,null,null,null,null,null,null,null,null,null);

Pattern = "\d{4}-\d{2}-\d{2}" Replace String = "2018-03-14"

But the above command is not working for me.. What did I wrong??

SST
  • 2,054
  • 5
  • 35
  • 65
  • Possible duplicate of [How to extract text from a string using sed?](https://stackoverflow.com/questions/11568859/how-to-extract-text-from-a-string-using-sed) and [Why doesn't `\d` work in regular expressions in sed?](https://stackoverflow.com/questions/14671293/why-doesnt-d-work-in-regular-expressions-in-sed) – Sundeep Mar 14 '18 at 07:46
  • see also [Why does my regular expression work in X but not in Y?](https://unix.stackexchange.com/questions/119905/why-does-my-regular-expression-work-in-x-but-not-in-y) – Sundeep Mar 14 '18 at 07:47
  • try `ssed` it will ease your life ;-) – Allan Mar 14 '18 at 09:13

2 Answers2

2

Specify range of digits as a character class [0-9]:

sed -En 's/[0-9]{4}-[0-9]{2}-[0-9]{2}/2018-03-14/gp' date.txt
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
1

You can also use ssed (super sed) if you want to use perl regex:

$ echo '2011-03-02' | ssed -Rn 's/\d{4}-\d{2}-\d{2}/2018-03-14/gp'
2018-03-14

It is less portable but more powerful, so you have to chose as always between flexibility or features/performances.

Allan
  • 12,117
  • 3
  • 27
  • 51