Functions to add LISP-like commands to KSH

The first function is ‘nth’ takes up to 4 parameters and displays those columns in the order specified:

echo "one two three four five" | nth 4 2 5
four two five

The next three functions (‘first’,’second’,’third’,’fourth’ respective field of output, executing a command if it is specified. Here is an example:

lspv | grep rootvg
hdisk0         00033f4a41bd5e90           rootvg          active
hdisk2         00033f4a23178559           rootvg          active

Without any parameters, ‘first’ simply strips off the other fields:

lspv | grep rootvg | first
hdisk0
hdisk2

With parameters, it simply applies them (like the lisp mapcar function) using xargs -n1 to create a bunch of sub-commands:

lspv | grep rootvg | first lsdev -Cl
hdisk0 Available  Virtual SCSI Disk Drive
hdisk2 Available  Virtual SCSI Disk Drive

The above command is literally two commands in one:

lsdev -Cl hdisk0 ; lsdev -Cl hdisk1

second and third are similar.

#!/bin/ksh

###################################
# Title         : functions.ksh
# Auithor       : John Rigler
# Date          : 10-22-2009
# Requires      : ksh and a .profile
###################################
# nth           : display fields
# first         : display/exec
# second        : display/exec
# third         : display/exec
# fourth        : display/exec
# ltrim         : discard X
# linesel       : show one line X
###################################



# This just wraps around awk and prints
# whatever fields are specified

function nth {
if [[ -n $4 ]]
        then
        awk "{print \$$1 , \$$2 , \$$3 , \$$4 }"
        exit
        fi

if [[ -n $3 ]]
        then
        awk "{print \$$1 , \$$2 , \$$3 }"
        exit
        fi

if [[ -n $2 ]]
        then
        awk "{ print \$$1 , \$$2 }"
        exit
        fi

if [[ -n $1 ]]
        then
        awk "{ print \$$1 }"
        exit
        fi

}

# These functions only display one field
# but will do an execution of anything
# specified, similar to mapcar in lisp

function first {

nth 1 | xargs -n1 $*

}

function second {

nth 2 | xargs -n1 $*

}

function third {

nth 3 | xargs -n1 $*

}

function fourth {

nth 4 | xargs -n1 $*

}


# This is a filter that drops X number of fields
# it does not work with multiple lines yet

function ltrim {

NEWLINE=""
let COUNT=0

read LINE
for WORD in $LINE
        do
        let COUNT=COUNT+1
        if [[ $COUNT -gt $1 ]]
                then
                NEWLINE="$NEWLINE $WORD"
                fi
        done

echo $NEWLINE

}

# A filter that simply selects only the line you specify

function linesel {

head -$1 | tail -1
}

Leave a Reply

Your email address will not be published. Required fields are marked *