1848590 Members
3346 Online
104033 Solutions
New Discussion

Re: Search and replace

 
Arun Kalasapudi
New Member

Search and replace

How can I use awk/perl/sed to convert all string of the following format in a text file.

Current:
3/19/2004-7:10:11

Convert to:
2004-3-19 7:10:11

Thanks.
6 REPLIES 6
Steven E. Protter
Exalted Contributor

Re: Search and replace

var1="3/19/2004-7:10:11"
var2="2004-3-19 7:10:11"

sed s/${var1}/${var2}/g $filename

Should work, make sure the file is backed up.

SEP

Steven E Protter
Owner of ISN Corporation
http://isnamerica.com
http://hpuxconsulting.com
Sponsor: http://hpux.ws
Twitter: http://twitter.com/hpuxlinux
Founder http://newdatacloud.com
Arun Kalasapudi
New Member

Re: Search and replace

Thanks Steven, I should have been more specific. I need to reformat the string while preserving the text rather than replacing the occurrences.
curt larson_1
Honored Contributor

Re: Search and replace

here is one that doesn't use any of those

cat yourFile |
while read Line
do
end=${Line#*\>}
start=${Line%$end}
last=${end#*\<}
arg=${end%$last}
hms=${arg#-*}
Date=${arg%*-}
print $Date | tr "/" " " | read Mon Day Year
print "${start}${Year}-${Mon}-${Day} ${hms}${last}"
done
curt larson_1
Honored Contributor

Re: Search and replace

using sed

sed 's/\(.*>\)\(.*\)\/\(.*\)\/\(.*\)-\(.*\)/\1\4-\3-\2 \5/'
curt larson_1
Honored Contributor

Re: Search and replace

using awk

cat yourFile |
awk '{
split($0,a,">");
start=sprintf("%s>,a[1])'
split($0,a,"<");
last=sprintf("<%s,a[3])'
sub(start,"");
sub(last,"");
split($0,a,"-");
hms=a[2];
split(a[1],b,"/");
printf("%s%s-%s-%s %s%s\n",start,b[3],b[2],b[1],hms,last);
}'
curt larson_1
Honored Contributor

Re: Search and replace

using perl

perl -ne '
s|(<.*>)(\d*)/(\d*)/(\d*)-(.*)(<.*)|$1$4-$3-$2 $5$6|;
print;
' yourFile