I have two data files with date stamps in different formats (as text in the file contents). I wish to compare the two dates and print the variable from one file to another according to date in a shell script. I have a script in MATLAB, but I’d like to do it in a shell script. In one file, the date format is 2017-01-01 12:00:00
. In the other file it is 20170101 1200
. For a variable I want to compare it with date in file1
and if it matches print variable as column in file1
from file2
.
1 Answer
You can do this in plain bash with parameter substitution:
dateA='2017-01-01 12:00:00' dateB='20170101 1200' tmpA=${dateA//[-:]/} # remove hyphens and colons # next expansion excludes last 2 characters [[ "${tmpA:0:-2}" == "$dateB" ]] && echo same || echo different
same
Older bash versions don't support negative lengths, but you can use ${tmpA:0:${#tmpA}-2}
man date
, and use the--date=
and--format=
options to convert both dates to "seconds since the epoch".file1
20 characters long (e.g.,2017-01-01 12:00:00
and a newline, and nothing else)? Isfile2
14 characters long (e.g.,20170101 1200
and a newline, and nothing else)? If not, you haven't shown us samples of your input files. (2) Show what output you want/expect. (3) Show us your MATLAB script. (P.S. Does it work the way you want?) (4) Try to do this in a shell script, and show us your best attempt. … … … … … … … … … … … … … Please do not respond in comments; edit your question to make it clearer and more complete.