PDA

View Full Version : sed question(switching characters)?


cdlaforc
21st March 2006, 05:21 PM
Maybe not exactly programming but does anyone know how with sed to change a date like 03/20/2006 to 2006-03-20?

Shakes
21st March 2006, 06:20 PM
I can't rememer how to use sed much so here's a bash script especially for you

Save the following in a file called dateConverter.sh (the web site won't let me upload files of this type). Do a "chmod u+x dateConverter.sh". Then run it with your date as an a parameter.


#Converts dates from mm/dd/yyyy to yyyy-mm-dd
#by Shakes

if [ $# -eq 0 ]; then
echo "Usage: dateConvert.sh mm/dd/yyyy"
exit 1
fi

IFS="/"
index=1

for x in ${1}
do
datePart[$index]=$x
let index=$index+1
done

echo ${datePart[3]}-${datePart[1]}-${datePart[2]}


I could clearly make this cleverer and start let u speify abitrary formats and things but hopefully it'll match ur needs.

Jman
22nd March 2006, 06:19 PM
date command makes this easy: date -d "03/20/2006" +%F See the man page and date --help for more info.

Shakes
22nd March 2006, 06:22 PM
damn I didn't realise that the date command could take date as input. Still nice to do some bash again :-)

cdlaforc
22nd March 2006, 06:27 PM
Hey,
Thanks everyone. I actually decided to do it with awk. Pretty easy that way.

function chgDate(STRING){
newDate=substr(STRING,7,4) "-" substr(STRING,1,2) "-" substr(STRING,4,2)
return newDate
}
{
if (NR > 1) {
printf "insert into tbl_runTime1 values(%s,'%s','%s','%s','%s','%s');\n", $1,$2,$3,$4,chgDate($5),$6
}
}

Duisburg Travel Photos on Instagram - Mauritania Instagram Photos - Algeria Travel Photos -