shell script to get year, date and month from YYYY-MM-DD format - shell

I am running a shell script which accepts date in "YYYY-MM-DD" format. from this date input, how can i get year, month and day separately?
Thanks for replies in advance.

except for processing the string as text(with grep/sed/awk/cut/...), you could do with with date command:
kent$ date -d '2013-09-06' +%Y
2013
kent$ date -d '2013-09-06' +%m
09
kent$ date -d '2013-09-06' +%d
06

You could do this to store them on variables with one command:
read YEAR MONTH DAY < <(date -d '2013-09-06' '+%Y %m %d')
printf "%s\n" "$YEAR" "$MONTH" "$DAY"

Try this :
dt="2011-2-3"
arr=( $( date --date=$dt "+%Y %m %d") )
echo "Year > $arr"
echo "Month > ${arr[1]}"
echo "Month > ${arr[2]}"

I didn't want to use date command, so I got the following code. It uses awk, which I feel is more appropriate for this task. I assumed you want to store results in variables.
inputDate=2017-07-06
year=`echo $inputDate | awk -F\- '{print $1}'`
month=`echo $inputDate | awk -F\- '{print $2}'`
day=`echo $inputDate | awk -F\- '{print $3}'`

Related

How can we get weekday based on given date in unix

From a given date in %m-%d-%Y format we should determine what day it is.
Example: for the date 09-01-2017 output should be Friday
Very simple. Just use the date command itself with correct options.
$ date -j -f '%m-%d-%Y' "09-01-2017" +'%A'
Friday
If you have your date like this:
d="09-01-2017"
you need to reformat it to "YYYY-MM-DD"
date -d $(echo $d|awk -F- '{print $3 "-" $1 "-" $2}') +%A # DOW
Here is what I usually do. I would use the date function.
you can do 'man date' and find options.
$ d=2020-08-20 \
$ date -d "$d" +%u \
4 \
$ date -d "$d" +%A \
Thursday
DayOfWeek=$(date +%A)
This would yield the day of week monday-sunday
If your input date is strictly in the format MM-DD-YYYY, use the following
IFS='-' read -ra ADDR <<< "09-01-2017"
formattedDate=${ADDR[2]}-${ADDR[0]}-${ADDR[1]}
date -d $formattedDate +%A
The first line tokenizes the components of the date and the second rearranges them
You can pass it as %m/%d%Y which gets recognized by the date command.
$ date --date="`echo 09-01-2017| sed -e 's/-/\//g' `" +'%A'
Friday
To verify it, pass %F to get it in ISO format
$ date --date="`echo 09-01-2017| sed -e 's/-/\//g' `" +'%A %F'
Friday 2017-09-01
date +%A
# let us see in a for loop
for i in {1..7}; do date +%A --date=+${i}day; done
Wednesday
Thursday
Friday
Saturday
Sunday
Monday
Tuesday

Declare date using awk

I need help in completing the below script in shell.
Requested format is to print previous, current and next business days (should exclude weekends and holidays).
text name : holiday.txt
#!/usr/bin/sh
cur_date=`date +"%A %m/%d/%Y"`
cur_day=`date +"%A"`
yesterday=`TZ=AEDT+13 date +"%A %m/%d/%Y"`;
twodd_back=`TZ=AEDT+37 date +"%A %m/%d/%Y"`;
tomorrow=`TZ=AEDT-35 date +"%A %m/%d/%Y"`;
twodd_later=`TZ=AEDT-59 date +"%A %m/%d/%Y"`;
cdate=`date +"%m/%d/%Y"`
####################
echo "Previous Business Day is $yesterday"
if echo $yesterday|awk '{print $1}'=Saturday
then echo "Previous Business Day is $twodd_back"
fi
echo "Current Business Day is $ cur_date"
echo " Next Business Day is $tomorrow"
The script in its current status does not execute successfully. It fails with below error.
awk: syntax error at source line 1
context is
{print >>> $1}= <<< Saturday
awk: bailing out at source line 1
To fix it, change your if statement.
if [[ `echo $yesterday | awk '{print $1}'` = Saturday ]];

Parsing date and time format - Bash

I have date and time format like this(yearmonthday):
20141105 11:30:00
I need assignment year, month, day, hour and minute values to variable.
I can do it year, day and hour like this:
year=$(awk '{print $1}' log.log | sed 's/^\(....\).*/\1/')
day=$(awk '{print $1}' log.log | sed 's/^.*\(..\).*/\1/')
hour=$(awk '{print $2}' log.log | sed 's/^\(..\).*/\1/')
How can I do this for month and minute?
--
And I need that every line of my log file:
20141105 11:30:00 /bla/text.1
20141105 11:35:00 /bla/text.2
20141105 11:40:00 /bla/text.3
....
I'm trying read line by line this log file and do this:
mkdir -p "/bla/backup/$year/$month/$day/$hour/$minute"
mv $file "/bla/backup/$year/$month/$day/$hour/$minute"
Here is my not working code:
#!/bin/bash
LOG=/var/log/LOG
while read line
do
year=${line:0:4}
month=${line:4:2}
day=${line:6:2}
hour=${line:9:2}
minute=${line:12:2}
file=$(awk '{print $3}')
if [ -f "$file" ]; then
printf -v path "%s/%s/%s/%s/%s" $year $month $day $hour $minute
mkdir -p "/bla/backup/$path"
mv $file "/bla/backup/$path"
fi
done < $LOG
You don't need to call out to awk to date at all, use bash's substring operations
d="20141105 11:30:00"
yr=${d:0:4}
mo=${d:4:2}
dy=${d:6:2}
hr=${d:9:2}
mi=${d:12:2}
printf -v dir "/bla/%s/%s/%s/%s/%s/\n" $yr $mo $dy $hr $mi
echo "$dir"
/bla/2014/11/05/11/30/
Or directly, without all the variables.
printf -v dir "/bla/%s/%s/%s/%s/%s/\n" ${d:0:4} ${d:4:2} ${d:6:2} ${d:9:2} ${d:12:2}
Given your log file:
while read -r date time file; do
d="$date $time"
printf -v dir "/bla/%s/%s/%s/%s/%s/\n" ${d:0:4} ${d:4:2} ${d:6:2} ${d:9:2} ${d:12:2}
mkdir -p "$dir"
mv "$file" "$dir"
done < filename
or, making a big assumption that there are no whitespace or globbing characters in your filenames:
sed -r 's#(....)(..)(..) (..):(..):.. (.*)#mv \6 /blah/\1/\2/\3/\4/\5#' | sh
date command also do this work
#!/bin/bash
year=$(date +'%Y' -d'20141105 11:30:00')
day=$(date +'%d' -d'20141105 11:30:00')
month=$(date +'%m' -d'20141105 11:30:00')
minutes=$(date +'%M' -d'20141105 11:30:00')
echo "$year---$day---$month---$minutes"
You can use only one awk
month=$(awk '{print substr($1,5,2)}' log.log)
year=$(awk '{print substr($1,0,4)}' log.log)
minute=$(awk '{print substr($2,4,2)}' log.log)
etc
I guess you are processing the log file, which each line starts with the date string. You may have already written a loop to handle each line, in your loop, you could do:
d="$(awk '{print $1,$2}' <<<"$line")"
year=$(date -d"$d" +%Y)
month=$(date -d"$d" +%m)
day=$(date -d"$d" +%d)
min=$(date -d"$d" +%M)
Don't repeat yourself.
d='20141105 11:30:00'
IFS=' ' read -r year month day min < <(date -d"$d" '+%Y %d %m %M')
echo "year: $year"
echo "month: $month"
echo "day: $day"
echo "min: $min"
The trick is to ask date to output the fields you want, separated by a character (here a space), to put this character in IFS and ask read to do the splitting for you. Like so, you're only executing date once and only spawn one subshell.
If the date comes from the first line of the file log.log, here's how you can assign it to the variable d:
IFS= read -r d < log.log
eval "$(
echo '20141105 11:30:00' \
| sed 'G;s/\(....\)\(..\)\(..\) \(..\):\(..\):\(..\) *\(.\)/Year=\1\7Month=\2\7Day=\3\7Hour=\4\7Min=\5\7Sec=\6/'
)"
pass via a assignation string to evaluate. You could easily adapt to also check the content by replacing dot per more specific pattern like [0-5][0-9] for min and sec, ...
posix version so --posix on GNU sed
I wrote a function that I usually cut and paste into my script files
function getdate()
{
local a
a=(`date "+%Y %m %d %H %M %S" | sed -e 's/ / /'`)
year=${a[0]}
month=${a[1]}
day=${a[2]}
hour=${a[3]}
minute=${a[4]}
sec=${a[5]}
}
in the script file, on a line of it's own
getdate
echo "year=$year,month=$month,day=$day,hour=$hour,minute=$minute,second=$sec"
Of course, you can modify what I provided or use answer [6] above.
The function takes no arguments.

Return yesterday's date in shell script using awk or echo

I am sure there is a simple answer to this :
Why does the following not give me the date and time in a script? What should I use rather than awk? Awk works fine if I need to query files but I guess it is the wrong thing to use here..
Code :
$ySTD=$(date --date yesterday "+%Y-%m-%d") | awk '{print substr($1,1,10)}'
echo ${ySTD}
echo 'STD calculated from DATE - last 24 hrs data will be fetched'
${ySTM}=$(date --date yesterday "+%T")| awk '{print substr($1,1,5)}'
echo ${ySTM}
In the shell I get this when the script runs:
+ awk '{print substr($1,1,10)}'
++ date --date yesterday +%Y-%m-%d
+ =2014-07-03
logdat3: line 41: =2014-07-03: command not found
+ echo
+ echo 'STD calculated from DATE - last 24 hrs data will be fetched'
STD calculated from DATE - last 24 hrs data will be fetched
+ awk '{print substr($1,1,5)}'
++ date --date yesterday +%T
+ =11:33:34
logdat3: line 45: =11:33:34: command not found
+ echo
Many thanks in advance
You're rigth, no awk needed:
$ read ySTD ySTM < <(date --date yesterday "+%Y-%m-%d %T")
$ echo $ySTD
2014-07-03
$ echo $ySTM
12:16:37
Anyway , your original code fixed:
ySTD=$(date --date yesterday "+%Y-%m-%d")
echo ${ySTD}
echo 'STD calculated from DATE - last 24 hrs data will be fetched'
ySTM=$(date --date yesterday "+%T")
echo ${ySTM}
You don't need to get a substring.

Shell Script for Yesterdays Date

I have tried adding -d "yesterday" but I haven't had any luck getting it to work. Here is what I have for the whole script:
#! /bin/bash
saveDir="TJ"
dd=$(date +"%m-%d-%Y")
for file in *.csv ; do
saveName="${saveDir}/TJ ${dd}.csv"
cut -d',' -f2,14 "$file" > "$saveName"
done
how do I get dd to output yesterdays date instead of the current date?
EDIT: This is what I have now
#! /bin/bash
saveDir="TJ"
dd=$(date --date='yesterday' +'%m-%d-%Y')
for file in *.csv ; do
saveName="${saveDir}/TJ ${dd}.csv"
cut -d',' -f2,14 "$file" > "$saveName"
done
the above is saving the file as TJ .csv but I'm not sure what was done incorrectly
I think you want to use -
$ cat test.sh
#!/bin/bash
dd=$(date --date='yesterday' +'%m-%d-%Y')
echo $dd
$ ./test.sh
12-31-2013
or you could use
$ date -d '1 day ago' +'%m-%d-%Y'
12/31/2013
And for tomorrow -
$ date -d '1 day' +'%m-%d-%Y'
01/02/2014
or
$ date --date='tomorrow'
Thu Jan 2 21:25:00 EST 2014
Get today's date in seconds since epoch. Subtract 86400 to get to yesterday. Then convert yesterday to the string format you want.
today=`date +"%s"`
yesterday=`expr $today - 86400`
dd=`date --date="#${yesterday}" +"%m-%d-%Y"`
Try this
yday=$(date --date yesterday "+%d-%m-%Y")
echo $yday
And If you works in Linux
yday=$(date -d "-1 days" +"%d-%m-%Y")
echo $yday
I tried date -d "yesterday" +%m-%d-%Y on my Linux, it worked fine.
If you are on unix platform, you cannot use -d,
you can get yesterday's date using perl, this is how I do using perl
dd=$(perl -e '($a,$b,$c,$day,$mon,$year,$d,$e,$f) = localtime(time-86400);printf "%02d-%02d-%4d",$day, $mon+1, $year+1900')
echo $dd
01-01-2014
NewDate=`date +"%A %d %B %Y" --date="-1 day"`
echo $NewDate
this will give your yesterday's date (-1)
This will give you tomorrow's date (+1)
even you can check for any values like (+/-) days

Resources