Convert unix date to integer value - unix

hi i have my UNIX file date in particular format 2017-02-01 i want to convert it in integer value like 20170201. What can i do get this output.My UNIX box is(SunOS 5.10).I tried to check below command to see what they output.But i am not getting anything.Can anyone help?
bash-3.2$ date +'%s'
%s
bash-3.2$ date +"%s"
%s
bash-3.2$ date +%s
%s
When i try date -d "Filename" +%Y%m%d option it error out saying:-
date: bad conversion
usage: date [-u] mmddHHMM[[cc]yy][.SS]
date [-u] [+format]
date -a [-]sss[.fff]

You can get the date you like with this line of code (bash):
date +"%Y%m%d"
you can use it as a filename like this:
_now=$(date +"%Y%m%d")
_file="/tmp/$_now.ext"
then use $_file for your filename

SunOS 5.10 (Solaris 10) is pretty old. There are some things it doesn't do.
In particular, I note that its date command relies on strftime() for formatting, and according to the man page, Solaris 10's strftime does not support %s. Which explains the results in the test you did in your question.
If you really just want a YYYYMMDD format, the following should work:
$ date '+%Y%m%d'
If you're looking for an epoch second, then you might have to use some other tool. Nawk, for example, should be installed on your system:
$ nawk 'BEGIN{print srand}'
You can man nawk and search for srand to see why this works.
Alternately, you could use Perl, if you've installed it:
$ perl -e 'print time . "\n";'
These are strategies to get the current epoch second, but your initial date command is the correct way to get the date formatted the way you suggested.
Based on other comments, it also appears you're looking to get the timestamp of certain files. That's not something the date command will do. In other operating systems, like Linux or FreeBSD, you'd use the stat command, which does not appear as a separate shell command in Solaris 10.
But you can do it yourself in a pretty short C program that uses the fstat(2) system call. While it may be beyond the scope required for this question, you can probably compile this using /usr/sfw/bin/gcc:
#include <stdio.h>
#include <time.h>
#include <fcntl.h>
#include <sys/stat.h>
int main(int argc, char **argv)
{
struct tm info;
char buf[80];
struct stat fileStat;
time_t epoch;
if(argc != 2)
return 1;
int file=0;
if((file=open(argv[1],O_RDONLY)) < -1)
return 1;
if(fstat(file,&fileStat) < 0)
return 1;
info = *localtime( &fileStat.st_mtime );
epoch = mktime(&info);
printf("%s:%ld\n", argv[1], (long) epoch );
return 0;
}
For example:
$ gcc -o filedate filedate.c
$ ./filedate /bin/ls
/bin/ls:1309814136
$ perl -e 'use POSIX; print POSIX::strftime("%F %T\n", gmtime(1309814136));'
2011-07-04 21:15:36
$ ls -l /bin/ls
-r-xr-xr-x 1 root bin 18700 Jul 4 2011 /bin/ls
$

SOLVED IT WITH THIS COMMAND-:
browserDate="2016-11-21"
dateConversion="${browserDate//'-'}"

Related

Which shell will execute the cmd when popen is called

First of all, forgive my awful english.....
This is the prototype
FILE *popen(const char* cmd_string, const char* type);
Here is my question, the book says that when popen function is called, it will call exec to get a shell to execute the cmd_string we give to popen, but I'm not sure which shell will exec get, so can anyone give me an answer?
/bin/sh : From the doc:
The command argument is a pointer to a null-terminated string
containing a shell command line. This command is passed to /bin/sh
using the -c flag; interpretation, if any, is performed by the shell.
Let's try and see:
$ cat test.c
#include <stdio.h>
int main() {
FILE *fp;
char var[5];
fp = popen("echo $0", "r");
fgets(var, 5, fp);
printf("%s", var);
}
$ gcc -Wall test.c
$ ./a.out
sh

what's the difference between cat file and cat < file

The way I understand this is that the command
cat file
will display the contents of file and
cat < file
will take the contents of file as input. I was trying this out and created two files. One called file1.txt and another one called file2.txt. In file1.txt, I wrote file2.txt, so by typing the command
cat < file1.txt
, I am expecting the content of file2.txt to be displayed; however , both
cat file1.txt and cat < file1.txt
are displaying the content of file1.txt. I think I am misunderstanding the definition of <.
When cat is run with argument files, it will open and read from each of these files to standard output. So with cat file1.txt, cat opens file1.txt and print its contents to standard output:
$ cat file1.txt
file2.txt
When cat is run with no argument files, it will read from standard input (e.g., as if you typed directly to cat) and write to standard output. But < file1.txt tells the shell (e.g., bash) to open the file file1.txt, and redirect it to cat through standard input:
$ cat < file1.txt
file2.txt
As you can see, the effect is the same, that cat will read the file given; the difference is who opens the file. In the first case, cat gets told to open the file itself, while in the second case the shell opens it, and cat doesn't know anything except that there's a stream of data coming in through its standard input, that it is supposed to print.
Finally, if you want to use the contents of file1.txt as an argument to cat, you need to use the syntax
$ cat $(< file1.txt) # same as: cat file2.txt
[...contents of file2.txt]
If you pass one or more file names, cat will display the contents of those files. Otherwise, it will print whatever it is passed on stdin.
cat file
cat receives one file name, opens the file, and prints its contents
cat < file
The shell redirects stdin to the named file: it opens the file and feeds its contents to cat on stdin. cat receives no arguments. Without arguments, it prints whatever's on stdinā€”the contents of the file.
Net result: cat file and cat < file do the same thing.
Let see the concept of cat from its roots, say from plan9 (the evolved roots):
# \sys\src\cmd\cat.c
#include <u.h>
#include <libc.h>
void
cat(int f, char *s)
{
char buf[8192];
long n;
while((n=read(f, buf, (long)sizeof buf))>0)
if(write(1, buf, n)!=n)
sysfatal("write error copying %s: %r", s);
if(n < 0)
sysfatal("error reading %s: %r", s);
}
void
main(int argc, char *argv[])
{
int f, i;
argv0 = "cat";
if(argc == 1)
cat(0, "<stdin>");
else for(i=1; i<argc; i++){
f = open(argv[i], OREAD);
if(f < 0)
sysfatal("can't open %s: %r", argv[i]);
else{
cat(f, argv[i]);
close(f);
}
}
exits(0);
}
It's clear from the sources that if you give < file as argment to cat it reads from stdin (f=0) and writes to stdout (1):
while((n=read(f, buf, (long)sizeof buf))>0)
if(write(1, buf, n)!=n)

Faster Alternative to Unix Grep

I'm trying to do the following
$ grep ">" file.fasta > output.txt
But it is taking so long when the input fasta file is large.
The input file looks like this:
>seq1
ATCGGTTA
>seq2
ATGGGGGG
Is there a faster alternative?
Use time command with all these
$> time grep ">" file.fasta > output.txt
$> time egrep ">" file.fasta > output.txt
$> time awk '/^>/{print $0}' file.fasta > output.txt -- If ">' is first letter
If you see the output..they are almost the same .
In my opinion ,if the data is in columnar format, then use awk to search.
Hand-built state machine. If you only want '>' to be accepted at the beginning of the line, you'll need one more state. If you need to recognise '\r' too, you will need a few more states.
#include <stdio.h>
int main(void)
{
int state,ch;
for(state=0; (ch=getc(stdin)) != EOF; ) {
switch(state) {
case 0: /* start */
if (ch == '>') state = 1;
else break;
case 1: /* echo */
fputc(ch,stdout);
if (ch == '\n') state = 0;
break;
}
}
if (state==1) fputc('\n',stdout);
return 0;
}
If you want real speed, you could replace the fgetc() and fputc() by their macro equivalents getc() and putc(). (but I think trivial programs like this will be I/O bound anyway)
For big files, the fastest possible grep can be accomplished with GNU parallel. An example using parallel and grep can be found here.
For your purposes, you may like to try:
cat file.fasta | parallel -j 4 --pipe --block 10M grep "^\>" > output.txt
The above will use four cores, and parse 10 MB blocks to grep. The block-size is optional, but I find using a 10 MB block-size quite a bit faster on my system. YRMV.
HTH
Ack is a good alternative to grep to find string/regex in code :
http://beyondgrep.com/

Unix If file exists, rename

I am working on a UNIX task where i want check if a particular log file is present in the directory or not. If it is present, i would like to rename it by appending a timestamp at the end. The format of the file name is as such: ServiceFileName_0.log
This is what i have so far but it wouldn't rename when i run the script, even though there is a file with the name ServiceFileName_0.log present.
renameLogs()
{
#If a ServiceFileName log exists, rename it
if [ -f $MY_DIR/logs/ServiceFileName_0.log ];
then
mv ServiceFileName_0.log ServiceFileName_0.log.%M%H%S
fi
}
Pls Help!
Thanks
renameLogs()
{
if [ -f $MY_DIR/logs/ServiceFileName_0.log ]
then mv $MY_DIR/ServiceFileName_0.log $MY_DIR/ServiceFileName_0.log.$(date +%M%H%S)
fi
}
Use the directory prefix consistently. Also you need to specify the time properly, as shown.
Better, though (less repetition):
renameLogs()
{
logfile="$MY_DIR/logs/ServiceFileName_0.log"
if [ -f "$logfile" ]
then mv "$logfile" "$logfile.$(date +%H%M%S)"
fi
}
NB: I've reordered the format from MMHHSS to the more conventional HHMMSS order. If you work with date components too, you should seriously consider using the ordering recommended by ISO 8601, which is [YYYY]mmdd. It groups all the log files for a month together in an ls listing, which is usually helpful. Using ddmm order means that the files for the first of each month are grouped together, then the files for the second of each month, etc. This is usually less desirable.
You might need to prefix the file name with the $MY_DIR path, just like you did in the test.
You could replace this:
mv ServiceFileName_0.log ServiceFileName_0.log.%M%H%S
with this
mv $MY_DIR/logs/ServiceFileName_0.log $MY_DIR/logs/ServiceFileName_0.log.%M%H%S
This isn't your apparent immediate problem, but the if construct is wrong: it introduces a time-of-check to time-of-use race condition. In between the if [ -f check and the mv, some other process could come along and change things so you can't move the file anymore even though the check succeeded.
To avoid this class of bugs, always write code that starts by attempting the operation you want to do, then if it failed, figure out why. In this case, what you want is to do nothing if the source file didn't exist, but report an error if the operation failed for any other reason. There is no good way to do that in portable shell, you need something that lets you inspect errno. I'd probably write this C helper:
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main(int argc, char **argv)
{
if (argc != 3) {
fprintf(stderr, "usage: %s source destination\n", argv[0]);
return 2;
}
if (rename(argv[1], argv[2]) && errno != ENOENT) {
fprintf(stderr, "rename '%s' to '%s': %s\n",
argv[1], argv[2], strerror(errno));
return 1;
}
return 0;
}
and then use it like so:
renameLogs()
{
( cd "$MY_DIR/logs"
rename_if_exists ServiceFileName_0.log ServiceFileName_0.log.$(date +%M%H%S)
)
}
The ( cd construct fixes your immediate problem, and unlike the other suggestions, avoids another race in which some other process comes along and messes with the logs directory or its parent directories.
Obligatory shell scripting addendum: Always enclose variable expansions in double quotes, except in the rare cases where you want the expansion to be subject to word splitting.

How do I determine if a terminal is color-capable?

I would like to change a program to automatically detect whether a terminal is color-capable or not, so when I run said program from within a non-color capable terminal (say M-x shell in (X)Emacs), color is automatically turned off.
I don't want to hardcode the program to detect TERM={emacs,dumb}.
I am thinking that termcap/terminfo should be able to help with this, but so far I've only managed to cobble together this (n)curses-using snippet of code, which fails badly when it can't find the terminal:
#include <stdlib.h>
#include <curses.h>
int main(void) {
int colors=0;
initscr();
start_color();
colors=has_colors() ? 1 : 0;
endwin();
printf(colors ? "YES\n" : "NO\n");
exit(0);
}
I.e. I get this:
$ gcc -Wall -lncurses -o hep hep.c
$ echo $TERM
xterm
$ ./hep
YES
$ export TERM=dumb
$ ./hep
NO
$ export TERM=emacs
$ ./hep
Error opening terminal: emacs.
$
which is... suboptimal.
A friend pointed me towards tput(1), and I cooked up this solution:
#!/bin/sh
# ack-wrapper - use tput to try and detect whether the terminal is
# color-capable, and call ack-grep accordingly.
OPTION='--nocolor'
COLORS=$(tput colors 2> /dev/null)
if [ $? = 0 ] && [ $COLORS -gt 2 ]; then
OPTION=''
fi
exec ack-grep $OPTION "$#"
which works for me. It would be great if I had a way to integrate it into ack, though.
You almost had it, except that you need to use the lower-level curses function setupterm instead of initscr. setupterm just performs enough initialization to read terminfo data, and if you pass in a pointer to an error result value (the last argument) it will return an error value instead of emitting error messages and exiting (the default behavior for initscr).
#include <stdlib.h>
#include <curses.h>
int main(void) {
char *term = getenv("TERM");
int erret = 0;
if (setupterm(NULL, 1, &erret) == ERR) {
char *errmsg = "unknown error";
switch (erret) {
case 1: errmsg = "terminal is hardcopy, cannot be used for curses applications"; break;
case 0: errmsg = "terminal could not be found, or not enough information for curses applications"; break;
case -1: errmsg = "terminfo entry could not be found"; break;
}
printf("Color support for terminal \"%s\" unknown (error %d: %s).\n", term, erret, errmsg);
exit(1);
}
bool colors = has_colors();
printf("Terminal \"%s\" %s colors.\n", term, colors ? "has" : "does not have");
return 0;
}
Additional information about using setupterm is available in the curs_terminfo(3X) man page (x-man-page://3x/curs_terminfo) and Writing Programs with NCURSES.
Look up the terminfo(5) entry for the terminal type and check the Co (max_colors) entry. That's how many colors the terminal supports.

Resources