You can do it in one line, but that begs the question -- "How long of a line do you want?" Since you have it labeled 'shell'
and not bash, etc., you are a bit limited in your string handling. POSIX shell provides enough to do what you want, but it isn't the speediest remedy. You are either going to end up with an awk
or sed
solution that calls date
or a shell solution that calls awk
or sed
to parse old date from the original file and feeds the result to date
to get your new date. You will have to work out which provides the most efficient remedy.
As far as the one-liner goes, you can do something similar to the following while remaining POSIX compliant. It simply uses awk
to get the 2nd field
from the file, pipes the result to a while
loop which uses expr length "$field"
to get the length and uses that within expr substr "$field" "2" <length expression - 2>
to chop the double-quotes from the end of the original date olddt
, followed by date -d "$olddt" +'%Y/%m/%d %H:%M:%S'
to get newdt
and finally sed -i "s;$olddt;$newdt;"
to perform the substitution in place. Your one-liner (shown with auto line-continuations for readability)
$ awk -F, '{print $2}' timefile.txt |
while read -r field; do
olddt="$(expr substr "$field" "2" "$(($(expr length "$field") - 2))")";
newdt=$(date -d "$olddt" +'%Y/%m/%d %H:%M:%S');
sed -i "s;$olddt;$newdt;" timefile.txt; done
Example Input File
$ cat timefile.txt
"item1","10/11/2017 2:10pm",1,2, ...
"item2","10/12/2017 3:10pm",3,4, ...
Resulting File
$ cat timefile.txt
"item1","2017/10/11 14:10:00",1,2, ...
"item2","2017/10/12 15:10:00",3,4, ...
There are probably faster ways to do it, but this is a reasonable length one-liner (relatively speaking).