How to code day of the month and send email in UNIX - unix

I am trying to make it so if I get emailed in the first 15 days of the month, I get a 0 and if I get emailed in the second half of the month, I get a 1.
currently I have
echo date + "%e"/30 | bc -l | mailx -s "Payday yet?" blah#gmail.com
I think I'm just not familiar how to work with the date

You can use shell test command ( or [ expr ] which does the same only with an extra ] as the last argument for sake of looking like a matching pair of brackets).
Something like this should do what you want:
[ `date +'%e'` -le 15 ]; FIRST_HALF=$?; mailx -s "Payday = $FIRST_HALF"

Related

i have to replace all the ? with X in unix except some valid?

It kind of some complicated question. I want to replace all the ? in the file with X. But the problem is there are some valid ? also there in input file.
eg:
input:
HELLO ?, WELCOME TO THE NEW WORLD??23, and you are most ? valid person.
output:
HELLO X, WELCOME TO THE NEW WORLDX?23, and you are most X valid person.
here, ? comes before 23 is valid one.. like ?23, many values are there. ?24,?33,?45, etc.,
I tried with sed script, but able to find the exact command.
Script which i used:
LINE_NUM=0
while IFS= read -r LINE
do
LINE_NUM=$?
EXTRACTED=`echo "${LINE}" |grep '?23' | sed 's|^.*\?23||; s|\?[0-9].*$||'`
if [ -n "$EXTRACTED" ]
then
UPDATED=`echo "$EXTRACTED" | sed 's/?/X/g'`
UPDATED_1=`echo "$UPDATED" | awk '{gsub("/","%",$0); print}'`
if [ $EXTRACTED != $UPDATED ]
then
LATEST_VALUE=`echo "${LINE}" | sed "s|${EXTRACTED}|${UPDATED}|g"`
fi
LATEST_VALUE=`echo "${LINE}"`
echo "$LATEST_VALUE" >> outputfile.txt
else
echo "$LINE" >> outputfile.txt
fi
done<inputfile.txt
$ echo "HELLO ?, WELCOME TO THE NEW WORLD??23, and you are most ? valid person." |
sed -E 's/\?([^0-9]|$)/X\1/g'
HELLO X, WELCOME TO THE NEW WORLDX?23, and you are most X valid person.
here it escapes ? followed by a digit (or end of line). If your list is more restricted change the regex there.
With your shown samples, please try following. In GNU awk please try following. Simple explanation would be, setting record separator as 1 ? followed by 1 digit, using global substitution to substitute ? with X in current records; setting correct output record separator as RT, then print current line.
awk -v RS='[?][0-9]' '{gsub(/\?/,"X");ORS=RT} 1' Input_file

How to log data of a call

I want to log data of asterisk command line. But the criteria is I want log data for calls separately, i.e. I want to log data for each call in separate file.
Is there a way to do that?
In case there is no inbuild feature in asterisk to do this, here is a bash solution:
#!/bin/bash
echo "0" >/tmp/numberoflines
IFS=''
pathToLogFile = /path/to/log/file
while [ 1 ]
do
NUMBER=$(cat /tmp/numberoflines)
LINECOUNT=$(wc -l < $pathToLogFile)
DIFFERENCE=$(($LINECOUNT-$NUMBER))
if [ $DIFFERENCE != 0 ]; then
lines=($(tail -n $DIFFERENCE $pathToLogFile))
for line in $lines; do
callID = `expr "$line" : 'CALLID_REGEX (see below)'`
$(echo "$line" >> /path/to/log/directory/$callID)
done
fi
sleep 5;
echo "$LINECOUNT" >/tmp/numberoflines
done
untested
it should be used to get ab idea to solve this problem.
the regular expression: normaly: /\[(C\d{8})\]/. sadly I don't know the syntax in bash. I'm sorry. you have to convert it by yourself into bash-syntax.
The idea is: remember the last line in the logfile that was processed by the bash script. check the line count of the log file. if there are more lines then the remembered line: walk through the new lines and extract the call id at the beginning of each line (format: C******** (* are numbers). in words: a C followed by a number with 8 digits). now append the whole line at the end of a log file. the name of the file is the extracted callid.
EDIT Information about the call id (don't mistake it with the caller id): https://wiki.asterisk.org/wiki/display/AST/Unique+Call-ID+Logging

RHL5 to Sunsolaries

Below code works in bash but it is not working in ksh.
Presently i am using RHL5 version os below code is working fine but in sunsolaries it is not working.
In sunsolaries we are using Korn Shell.
#!/bin/bash
#give start date and enddate in the format yyyy_mm_dd
startdate="${1//_/-}" # change underscores into dashes
enddate="${2//_/-}"
enddate=`date -d "$enddate + $i day" "+%Y_%m_%d"` #Increases enddate by 1 day so that loop runs on given enddate also
enddate="${enddate//_/-}"
echo "StartDate: $startdate EndDate+1Day: $enddate"
nextdate=$startdate #nextdate runs from startdate to enddate
while [ 1 ]
do
echo "$nextdate $enddate"
if [ "$nextdate" == "$enddate" ];then #after given enddate loop breaks
break
fi
day=`date -d "$nextdate"`
arr=(${day// / })
echo "${arr[0]}"
if [ "${arr[0]}" == "Sat" ];then #checking if day is Saturday, if true then increase nextday and continue
nextdate=`date -d "$nextdate + 1 day" "+%Y_%m_%d"`
nextdate="${nextdate//_/-}"
continue
fi
#####your code begins here
echo "creating file file_$nextdate.txt"
touch "file_$nextdate.txt" #test code, just creating files with date, remove this
#####your code ends here
nextdate=`date -d "$nextdate + 1 day" "+%Y_%m_%d"` #increasing nextday by 1 day
nextdate="${nextdate//_/-}"
done
Please help me how it works in ksh
Thanks
Your script is using several time the Gnu date specific -d option. Either find a different way to achieve what it does in you use case, or install Gnu date on the Solaris machine if it isn't already.

Check the date and time entered by user in UNIX

I have a Shell script which uses the date and time parameters entered by the user.
Date as mm/dd/yyyy and Time as HH:MM .
What would be the easiest means to check the user had entered the proper date [ like month should be less than 12.... for time MM should be less than 60...
Do we have any built in functions in UNIX for checking the timestamp?
You could use the unix date tool to parse and verify it for you, and test the return code e.g.
A valid date, return code of 0:
joel#bohr:~$ date -d "12/12/2000 13:00"
Tue Dec 12 13:00:00 GMT 2000
joel#bohr:~$ echo $?
0
An invalid date, return code 1:
joel#bohr:~$ date -d "13/12/2000 13:00"
date: invalid date `13/12/2000 13:00'
joel#bohr:~$ echo $?
1
You can vary the input format accepted by date by using the +FORMAT option (man date)
Putting it all together as a little script:
usrdate=$1
date -d "$usrdate" > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo "Date $usrdate was valid"
else
echo "Date $usrdate was invalid"
fi
You could use grep to check that the input conforms to the correct format:
if ! echo "$INPUT" | grep -q 'PATTERN'; then
# handle input error
fi
where PATTERN is a regular expressino that matches all valid inputs and only valid inputs. I leave constructing that pattern to you ;-).
(Late answer)
Something that you can use:
...
DATETIME=$1
#validate datetime..
tmp=`date -d "$DATETIME" 2>&1` ; #return is: "date: invalid date `something'"
if [ "${tmp:6:7}" == "invalid" ]; then
echo "Invalid datetime: $DATETIME" ;
else
... valid datetime, do something with it ...
fi

Converting dates in AWK

I have a file containing many columns of text, including a timestamp along the lines of Fri Jan 02 18:23 and I need to convert that date into MM/DD/YYYY HH:MM format.
I have been trying to use the standard `date' tool with awk getline to do the conversion, but I can't quite figure out how to pass the fields into the 'date' command in the format it expects (quoted with " or 's,) as getline needs the command string enclosed in quotes too.
Something like "date -d '$1 $2 $3 $4' +'%D %H:%M'" | getline var
Now that I think about it, I guess what I'm really asking is how to embed awk variables into a string.
If you're using gawk, you don't need the external date which can be expensive to call repeatedly:
awk '
BEGIN{
m=split("Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec",d,"|")
for(o=1;o<=m;o++){
months[d[o]]=sprintf("%02d",o)
}
format = "%m/%d/%Y %H:%M"
}
{
split($4,time,":")
date = (strftime("%Y") " " months[$2] " " $3 " " time[1] " " time[2] " 0")
print strftime(format, mktime(date))
}'
Thanks to ghostdog74 for the months array from this answer.
you can try this. Assuming just the date you specified is in the file
awk '
{
cmd ="date \"+%m/%d/%Y %H:%M\" -d \""$1" "$2" "$3" "$4"\""
cmd | getline var
print var
close(cmd)
}' file
output
$ ./shell.sh
01/02/2010 18:23
and if you are not using GNU tools, like if you are in Solaris for example, use nawk
nawk 'BEGIN{
m=split("Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec",d,"|")
for(o=1;o<=m;o++){
months[d[o]]=sprintf("%02d",o)
}
cmd="date +%Y"
cmd|getline yr
close(cmd)
}
{
day=$3
mth=months[$2]
print mth"/"day"/"yr" "$4
} ' file
I had a similar issue converting a date from RRDTool databases using rrdfetch but prefer one liners that I've been using since Apollo computer days.
Data looked like this:
localTemp rs1Temp rs2Temp thermostatMode
1547123400: 5.2788174937e+00 4.7788174937e+00 -8.7777777778e+00 2.0000000000e+00
1547123460: 5.1687014581e+00 4.7777777778e+00 -8.7777777778e+00 2.0000000000e+00
One liner:
rrdtool fetch -s -14400 thermostatDaily.rrd MAX | sed s/://g | awk '{print "echo ""\`date -r" $1,"\`" " " $2 }' | sh
Result:
Thu Jan 10 07:25:00 EST 2019 5.3373432378e+00
Thu Jan 10 07:26:00 EST 2019 5.2788174937e+00
On the face of it this doesn't look very efficient to me but this kind of methodology has always proven to be fairly low overhead under most circumstances even for very large files on very low power computer (like 25Mhz NeXT Machines). Yes Mhz.
Sed deletes the colon, awk is used to print the other various commands of interest including just echoing the awk variables and sh or bash executes the resulting string.
For methodology or large files or streams I just head the first few lines and gradually build up the one liner. Throw away code.

Resources