Improve your AWK experience

From BITS wiki
Jump to: navigation, search

Find here unsorted functions created to perform repetitive tasks. Some can be improved and you are welcome to feed back on errors you will find.


[ Main_Page ]

Create and use a cental file with custom AWK functions

Instead of having to retype custom functions in many of your scripts, instead create a function libray that you place in a central folder (in your home) and call in your awk code using @include and after defining a default AWKPATH. We proceed here in several steps

# create a, invisible folder where to save your custom function(s)
mkdir -p ~/.awk
 
# in your .bashrc, add this folder to your ENV under the name AWKPATH, this is the default PATH where ask will look for external files
export AWKPATH=~/.awk
 
# edit a new file (we call it here 'awkfun' in the .awk folder and put in it some custom function, 
# as example: the missing abs() function to get the absolute value of some number
function abs(value){
return (value<0?-value:value);
}
 
# add <@include "awkfun";> at the beginning of your code, betwen <'> and the opening brace '{'
# and the functions contained in that file will become available to the script
echo "-10" | awk '@include "awkfun"; {print $1, abs($1)}'
-10 10

Some AWK functions

compute the absolute value of numbers

function abs(value){
return (value<0?-value:value);
}

 



References:



[ Main_Page ]