Archive

Archive for March, 2011

Useless use of cat

March 26, 2011 Leave a comment

http://partmaps.org/era/unix/award.html

Above link looks dead.

But a search of “Useless Use of cat” gave the following results:

http://www.smallo.ruhr.de/award.html
https://en.wikipedia.org/wiki/Cat_%28Unix%29#Useless_use_of_cat

Advertisements
Categories: Interesting Tags: , ,

Writing 7zcat (works like zcat on *.7z files)

March 25, 2011 1 comment

Copied /bin/zcat to a file called /bin/7zcat


#!/bin/bash

PATH=${GZIP_BINDIR-'/bin'}:$PATH
exec 7z e -so -bd "$@" 2>/dev/null | cat

Categories: bash Tags: , ,

Insufficiently known POSIX shell features

March 25, 2011 Leave a comment
Categories: Interesting Tags: ,

10 Key Considerations for Your Mobile Web Design Strategy

March 25, 2011 Leave a comment
Categories: Interesting Tags:

Writing 7zless (works like zless on *.7z files)

March 25, 2011 Leave a comment

After working with some 7z files I got tired of the whole uncompress, compress cycle. So, I had a look at /bin/zless and realised that all I had to do was replace gzip with 7z. Now I have my very own 7zless.


#!/bin/bash

# Copyright (C) 1998, 2002, 2006, 2007 Free Software Foundation

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

PATH="${GZIP_BINDIR-'/bin'}:$PATH"; export PATH

version="zless (gzip) 1.3.12
Copyright (C) 2007 Free Software Foundation, Inc.
This is free software.  You may redistribute copies of it under the terms of
the GNU General Public License <http://www.gnu.org/licenses/gpl.html>.
There is NO WARRANTY, to the extent permitted by law.

Written by Paul Eggert."

usage="Usage: $0 [OPTION]... [FILE]...
Like 'less', but operate on the uncompressed contents of any compressed FILEs.

Options are the same as for 'less'.

Report bugs to <bug-gzip@gnu.org>."

case $1 in
--help)    exec echo "$usage";;
--version) exec echo "$version";;
esac

if test "${LESSMETACHARS+set}" != set; then
 # Work around a bug in less 394 and earlier;
 # it mishandles the metacharacters '$%=~'.
 space=' '
 tab='    '
 newline='
'
 LESSMETACHARS="$space$tab$newline'"';*?"()<>[|&^`#\$%=~'
 export LESSMETACHARS
fi

LESSOPEN="|gzip -cdfq -- %s"; export LESSOPEN
exec less "$@"

So I replaced gzip -cdfq with 7z e -so -bd


#!/bin/bash

version="7zless (7z) 1.0.0 "

usage="Usage: $0 [OPTION]... [FILE]...
Like 'less', but operate on the uncompressed contents of any FILEs that were compressed using 7z.
"

case $1 in
--help)    exec echo "$usage";;
--version) exec echo "$version";;
esac

if test "${LESSMETACHARS+set}" != set; then
 # Work around a bug in less 394 and earlier;
 # it mishandles the metacharacters '$%=~'.
 space=' '
 tab=' '
 newline='
'
 LESSMETACHARS="$space$tab$newline'"';*?"()<>[|&^`#\$%=~'
 export LESSMETACHARS
fi

LESSOPEN="|7z e -so -bd -y -- %s"; export LESSOPEN
exec less "$@" 2>/dev/null

And that’s it. Still needs some work but atleast I can view the contents of a file without having to extract it first.

Now just to figure out how to emulate –quiet mode in 7z (7-Zip version 4.57) so that it stops displaying “unneccesary” details. Now to write 7zcat!

Categories: bash Tags: , ,

Printing days of the month.

March 24, 2011 1 comment

I needed to have the dates of the month for reporting purposes. As time was not on my side, I had my collegue do this for me in python. Later on I managed to do this in bash. (NB: The sample code below does not give the exact same results.)

Here is the bash version.

#!/bin/bash
#=============================================================================
#
# FILE: create_dates.sh
#
# USAGE: create_dates.sh [MONTH] [YEAR]
#
# DESCRIPTION: Lists the days of the given month for the given year in the
#              following format yyyy-mm-dd. If either value is not specified
#              then the current MONTH and/or YEAR is used.
#
#=============================================================================

month="$1"
year="$2"

#=== FUNCTION ================================================================
#           NAME: usage
#    DESCRIPTION: Display usage information for this script.
#    PARAMETER 1: ---
#=============================================================================
function usage()
{
cat <<- EOT
Lists the days of a given month in yyyy-mm-dd format.

usage: $0 [MONTH] [YEAR] [--help]

Optional values
    MONTH -- the month to use
    YEAR -- the year to use
    help -- display this message
EOT
}

#-----------------------------------------------------------------------------
# Display usage
#-----------------------------------------------------------------------------
if [ "$1" == "--help" ]
then
    usage
    exit
fi

#-----------------------------------------------------------------------------
# Assign default values if needed.
#-----------------------------------------------------------------------------
if [ -z "$month" ]
then
    month=$(date "+%m")
fi

if [ -z "$year" ]
then
    year=$(date "+%Y")
fi

#-----------------------------------------------------------------------------
# main
#-----------------------------------------------------------------------------
for day in $(cal $month $year);
do  echo $day  | \
    sed -n -e "s/^[0-9]$/${year}-${month}-0&/" \
           -e "s/^[0-9][0-9]$/${year}-${month}-&/" \
           -e "/^${year}-/p" | sed "s/.*/&,0/"
done

And here is the verbose python version.

#!/usr/bin/python
"""Create a file containing the days in a given month, for a given year.

For a given month, create a two column csv file, the first column holds the
days in the month. The date format is YYYY-MM-DD. The second column holds data
values, they are all set to zero.

The following should be specified.
 year            The desired year.
 month           The desired month.
 output_file     The file to write the dates to.

Options:
 --help          Print this message and exit.

"""
import calendar
import sys
import getopt

USAGE_TEXT = """Usage: create_date_file.py year month output_file
For more verbose descriptions, use create_date_file.py --help """

def help():
 print >> sys.stderr, __doc__
 sys.exit(0)

def usage(code, msg=''):
 """Print usage or error.

 Keyword arguments:
 code -- The exit status code.
 msg -- The message to print out.

 """
 print >> sys.stderr, msg
 sys.exit(code)

def create_date_file(file, month, year):
 """Create date file.

 Keyword arguments:
 file -- The name of the file to write to.
 month -- The desired month.
 year -- The desired year.

 """
 # Get the last day of the month
 last_day = calendar.monthrange(year, month)[1]

 temp_file = open(file, 'wb')
 for day in range(1, last_day + 1):
 temp_file.write(str(year) + "-" + str(month).zfill(2) + "-" +
 str(day).zfill(2) +",0 \n")
 temp_file.close()

def main():
 try:
 opts, args = getopt.getopt(sys.argv[1:], '',
 ['help'])

 for opt, arg in opts:
 if opt in ('--help'):
 help()

 year = int(args[0])
 month = int(args[1])
 file = args[2]
 create_date_file(file, month, year)

 except getopt.error, msg:
 usage(1, msg)
 except IndexError:
 usage(1, USAGE_TEXT)
 except ValueError:
 usage(1, USAGE_TEXT)

if __name__ == '__main__':
 main()

 

 

Categories: bash Tags: ,

Posting source code in wordpress.com

March 24, 2011 Leave a comment

This took a while to find. And I blame my searching skills.

To post code in wordpress.com eg

#!/usr/bin/env python

import sys
print "Hello %s" % sys.argv[1]

Have a look at the wordpress.com support page.

http://en.support.wordpress.com/code/posting-source-code/

Categories: wordpress Tags: