Yogsototh

Multi-line grep

Posted in script by yogsototh on May 4, 2009

After many, many times I use many different tricks to implement a multi-line grep, I’ve done one myself I called it <code>mlegrep</code>:

#!/usr/bin/env zsh

separator='\n\n'
while [[ ${1[1]} = '-' ]]; do
    case ${1[2]} in
        F) separator="${1[3,-1]}" ; shift ;;
        *) print "unknown option : $1" >&2; exit 2 ;;
    esac
done

if (($#>1)); then     
    print   "usage: $0:t [-Fseparator] REGEXP [FILE ...]" >&2
    exit 1
fi

value="$1"
shift
perl -ne 'BEGIN{$/="'$separator'";} if ( $_ =~ m/'$value'/ ) { print }' "$@"

hope this help,
Y.

Add include directive to awk

Posted in script by yogsototh on July 30, 2008

With gawk, there exists the @include directive :
@include "fic"

But, when you work for a company which use a prehistoric version of awk, you could use my script (it is more a hack than a real program) :

#!/usr/bin/env zsh
if (($#<1)); then
    {
        echo "usage : $(basename $0) script.awk arg1 ... argN"
        echo "provide @include \"path/to/awk/file\" directive"
        echo "usefull for libraries"
    } >&2
    exit 1
fi

tmpScriptAwk="/tmp/$(basename $1)"

# see my blog entry about this function
function matche
{
    echo "$1" | egrep "$2" > /dev/null
}

# go into the same directory as the script (to find the good path)
cd $(dirname $1)

# read the script
IFS='
'
for ligne in $(cat $(basename $1) | sed 's/\\/\\\\/g'); do
    # transform @include "path/to/file" by the content of path/to/file.awk
     if matche "$ligne" "^@include \".*\"" ; then
         nomFic=$(echo $ligne | perl -p -e 's#\@include "(.*)"#$1#' )
        # verify if the file to include is readable
         if [ ! -r "$nomFic" ]; then
            # add the .awk prefix (as it is not necessary)
             nomFic="$nomFic.awk"
             if [ ! -r "$nomFic" ]; then
                 echo "$nomFic n'est pas accessible en lecture" >&2
                 exit 1
             fi
         fi
        # write the content of the included file
         cat $nomFic
     else
         echo $ligne
     fi
done > $tmpScriptAwk
shift
# run the script with the argument
awk -f $tmpScriptAwk "$@"

Hope this help, 😉

Blogged with the Flock Browser
Tagged with: , , , , ,