Scripts   Home

KSH - AWK CGI Script Example

Yeah, you can use just about anything to code a cgi and this proves it, a Korn shell and awk cgi for a document search on a small site. To get the script save the source of this page.

# Korn shell cgi for a grep search of files in directories.

# log the search host and query.
log_search () {
   print 'QUERY_STRING='$QUERY_STRING >> ${LOGFILE}
   print 'REMOTE_ADDR='$REMOTE_ADDR >> ${LOGFILE}
   print 'REQUEST_URI='$REQUEST_URI >> ${LOGFILE}
}

# HTML for top of search result page.
html_header () {
print 'Content-type: text/html\n\n'
print 'Search Results'
print 'HOME'
FORM_STRING=$( echo $WORDS | nawk '{gsub( "\\|","\+");print $0}' )
cat << EOF


EOF } # Result html links and words in context. html_links_and_context () { /usr/bin/nawk ' BEGIN {home="http://www.your.domain/"} {path=$0; sub (/\/your\/path\//,"",path); print ""path"
"; }' | sort -u -t '&' -k 0,1 } # Get the query string from one of the evironment variables. get_query () { /usr/bin/nawk '{ n=split ($0,EnvString,"&"); for (i = n; i>0; i--) { # debug print EnvString[i]; m=split (EnvString[i],formlist,"="); valuelist[formlist[1]]=formlist[2]; }; # debug for (y in valuelist) { print y, valuelist[y] }; x=gsub(/\%../," ",valuelist["query"]); # remove funny stuff. x=gsub(/[^ |a-zA-Z0-9]/," ",valuelist["query"]); x=gsub(/[\*\+]/," ",valuelist["query"]); print valuelist["query"]; }' } # Search information for usage. search_info () { print 'Search Tips: Only letters [A-Z] [a-z] [0-9] and space ' print 'can be used in the search, other characters are removed.
' } # If the search fails get the search words. search_fail () { print 'Fail to find search: '$REQUEST_URI >> ${LOGFILE} print '
NO RESULT: try each term separately, fewer terms or partial words.
' for term in $WORDS do print '   '$term'' done print '' exit } ###################### # Main export CODEDIR='/your/path/to/search' export ARTICLEDIR='/path/to/search' export LOGFILE='/path/log/search.log' log_search WORDS=$(print $REQUEST_URI | get_query) html_header search_info export FOUND_FILES="$CODEDIR/* $ARTICLEDIR/*" find_file () { for term in $WORDS do export FOUND_FILES=$( grep -il "$term" $FOUND_FILES ) ${FOUND_FILES:=search_fail} #Check for success done } find_file print '

Search Results

' for i in $FOUND_FILES do print $i | html_links_and_context done print ''