Replacing the Dates in a file

Hello Gurus,

I'm beginner in Shell scripting.
I got a requirement to write a script.

I have a file with below (similar) content

If you can observe above content, there are many date values existed (with different dates) in a format: ddMonyyyy

I have to write replace all these dates with another format: DD-MON-YY

I'm trying it to do in a single line command, but felt bit complexity.
Hence trying for shell script for same.
Could anyone please help me on above?

Thanks in advance.
VRN

For posted input, try:

sed 's#\([0-9][0-9]\)\([A-Z][a-z][a-z]\)\([1-2][0-9]\)\([0-9][0-9]\)#\1-\2-\4#g' file

Note that this will not work for all scenarios. But I guess it will give you an idea to come up with something of your own.

Hi Yoda,

Thanks much for your reply.

Yeah, I tried in the same way only.... But there should be an accurate way for replacing the dates only.

If you notice the file content contains another word

which is similar to date format, but not the date.

I have to omit such kind of keywords also in case file contains in any line.

Could someone suggest me the exact pattern which can accomplish the task pls?

Thanks in advance...

VRN

Here is an awk solution:

awk 'BEGIN{
   r= "[0-9][0-9](Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Nov|Dec)[12][0-9][0-9][0-9]"
}
$0 ~ r {
while(match($0,r)){
   printf "%s-%s-%s",substr($0,1,RSTART+1),
    toupper(substr($0, RSTART+2, 3)),
    substr($0, RSTART+5,RLENGTH-5);
        $0=substr($0,RSTART+RLENGTH);
}}1 ' infile

Try :

add/remove comments shown in code according to your need

awk 'BEGIN{
            m="Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"
            for(i=1;i<=split(m,A);i++)Mon[A]=sprintf("%02d",i)
          }
          {
		for(i=1;i<=NF;i++){
                        for(j in Mon){
                                       # example 01102012
                                       # if(gsub(j,Mon[j],$i))break
				       
				       # example 01-10-2012
				       # if(gsub(j,"-"Mon[j]"-",$i))break

				       # example 01-Oct-10 
				       if(gsub(j,"-"j"-",$i))
				       {
					 $i = substr($i,1,length($i)-4) substr($i,length($i)-1)
                                         break
                                       }
                                     }
                                  }
          }1' file

Thanks much Akshay/Chubler for your solution..

Could this be done with any unix command except AWK... because my team is not much familiar with AWK (in case of any future modifications)?

Thanks again...

You can use sed:

$ sed -r 's/([0-9][0-9])(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Nov|Dec)[12][0-9]([0-9][0-9])/\1-\U\2-\3/g' infile
Raheem: 20-JUN-85; Keeth: 23-DEC-13
Rakesh: 34Hgg4233 L009334622fsda
Harsha: 19-JAN-99 9849043244 Venkat: 04-MAR-00
LR224HYZA245; Ramu: 29-FEB-11
1 Like

wow.... got good stuff to learn in sed...

Thank you very much Chubler.....