Hello,
I have a file with a date field with various lengths. For example:
m/d/yyyy hh:mm or h:mm
mm/dd/yyyy hh:mm or h:mm
Is there a way using sed or awk to change the field to m/d/y ? I don't need the hours and minutes in that field, just the date in the proper format.
Thanks in advance.
Jack
Please post sample input and desired output.
I presume you have a file with content like below
12/12/2012 22:30
4/2/1987 20:00
and the output that you desire is like below:
12/12/2012
4/2/1987
If this is the case you can simply user awk or cut whatever you are comfortable with and give the delimiter as [[SPACE]]
sample for cut
cut -d " " -f1
sample for awk
awk -F " "'{print$1}'
If i did not understand your issue let me know with a sample please
Input is 7/10/2012 19:21 or 7/10/2012 1:01 or 7/1/2012 23:59 or 7/1/2012 1:01
Want it to be 7/10/2012
Fields may be 11/10/2012 01:01 but still need to be 11/10/2012.
How about this?
awk '{print $1}' input
assuming that there is no space anywhere in the date-only part...
Yoda
6
awk '{gsub(/[^0-9/ ]|[0-9]+:[0-9]+/,x);$1=$1}1' file
It could be done with sed (but I'm not going to bother).
With any shell that recognizes basic Bourne shell syntax:
while IFS="/ " read -r m d y extra
do printf "%02d/%02d/%s\n" "$m" "$d" "$y"
done < file
does the job.
The same thing in awk would be:
awk -F '[/ ]' '{printf("%02d/%02d/%s\n", $1, $2, $3)}' file
If a file named file contains:
1/1/2013 1:23
1/10/2012 12:25
11/1/2011 1:02:03
12/30/2020 05:06:07
either of the above will produce:
01/01/2013
01/10/2012
11/01/2011
12/30/2020
If you choose the awk script and you are using a Solaris/SunOS system, use /usr/xpg4/bin/awk
, /usr/xpg6/bin/awk
, or nawk
instead of awk
.
Oops, I hadn't noticed your 2nd posting where you said:
I have absolutely no idea how to write general code to determine that the day 1 should be printed as 10.
Should "12/9/2012" be also converted to "12/90/2012" instead of "12/09/2012"?