Wednesday, May 8, 2013

Unix - Append 0 to single digit date


Input file file.txt has dates in month/day/year format.
$ cat file.txt 
3/4/2013
3/10/2013
10/4/2013
12/10/2012
Required: Add prefix 0 to first and second field if its a single digit.

Awk solution:
$ awk 'BEGIN {FS=OFS="/"} 
    { 
 if (length($1) == 1) $1="0"$1
 if (length($2) == 1) $2="0"$2
        { print }
}' file.txt
Output:
03/04/2013
03/10/2013
10/04/2013
12/10/2012
Related posts:
- A newbie tutorial on Unix Awk
- Awk if else
- Convert date format in unix using awk and sed

6 comments:

© Jadu Saikia www.UNIXCL.com