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.

How to Download the Script

To get the script below save the source of this page as it renders the html bits in a browser so “what you see is not what you want.” # 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 '' print 'HOME' FORM_STRING=$( echo ${WORDS} | ${AWK} '{gsub( "\\|","\+");print $0}' ) cat << EOF


EOF } # Result html links and words in context. html_links_and_context () { ${AWK} ' 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 environment variables. get_query () { ${AWK} '{ 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 AWK=/usr/bin/nawk # Configure to awk, nawk, gawk 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 ''

Leave a Reply

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