Awk: Difference between revisions

From miki
Jump to navigation Jump to search
Line 15: Line 15:
eval $(awk 'BEGIN{printf "MY_VAR=value";}')
eval $(awk 'BEGIN{printf "MY_VAR=value";}')
echo $MY_VAR
echo $MY_VAR
</source>

* '''Hexadecimal conversion''' - Use <code>strtonum</code> to convert parameter:
<source lang="awk">
{
print strtonum($1); # decimal, octal or hexa (guessed from prefix)
print strtonum("0"$2); # To force octal
print strtonum("0x"$3); # To force hexadecimal
}
</source>
* '''Using environment variables''' - Use <code>ENvIRON["NAME"]</code>:
<source lang="awk">
{ print strtonum("0x"ENVIRON["STARTADDR"]); }
</source>
</source>

Revision as of 09:06, 15 March 2016

References

Awk Program Examples

ps al | awk '{print $2}'                                         # Print second field of ps output
arp -n 10.137.3.129|awk '/ether/{print $3}'                      # Print third field of arp output, if line contains 'ether' somewhere
getent hosts unix.stackexchange.com | awk '{ print $1 ; exit }'  # Print only first line, then exit
find /proc -type l | awk -F"/" '{print $3}'                      # Print second folder name (i.e. process pid)

Tips

  • Defining environment variable - Using an Awk script and Bash builtin eval
eval $(awk 'BEGIN{printf "MY_VAR=value";}')
echo $MY_VAR
  • Hexadecimal conversion - Use strtonum to convert parameter:
{
    print strtonum($1);       # decimal, octal or hexa (guessed from prefix)
    print strtonum("0"$2);    # To force octal
    print strtonum("0x"$3);   # To force hexadecimal
}
  • Using environment variables - Use ENvIRON["NAME"]:
{ print strtonum("0x"ENVIRON["STARTADDR"]); }