newline


Use awk to print the last N columns of a file or a pipe

In this post we will describe a way to print the last N number of columns in awk.

We will use this code as example, where we will print the last 2 columns only:


awk '{n = 2; for (--n; n >= 0; n--){ printf "%s\t",$(NF-n)} print ""}';
'

In the awk script we use the variable n to control how many columns we want to print. In the above example we initialized it  to the value 2 as that is the number of columns we want printed.

After, we use a for loop to iterate over the fields (in this case the last two fields) and we print them to the screen using printf "%s\t",$(NF-n) to avoid printing the new line character and to separate them with a tab character.

NF is a special variable in awk that holds the total number of fields available on that line. If you do not change the delimiter, then it will hold the number of words on the line.

$(NF-n) is the way we ask awk to gives us the variable value that is n places before the last.

Outside the loop we print "" to print the new line character between input rows.

Examples:

If we want to print the last two columns of the ls -l command we can do it as follows:


ls -l | awk '{i = 2; for (--i; i >= 0; i--){ printf "%s\t",$(NF-i)} print ""}';

If we want to print the last two columns of the /etc/passwd file we can do it as follows:


awk -F ':' '{i = 2; for (--i; i >= 0; i--){ printf "%s\t",$(NF-i)} print ""}' /etc/passwd;

Note that we change the delimiter with the command line argument -F ":"


Creating an MD5 hash of a string in bash

Make sure that you are not including the new line character (\n) as well in your string, there are cases where it might be included without you explicitly writing it.
For example if you use the output of an echo command in bash, it will automatically add a new line character to the end and will cause your hash to be not the one you would like to have.
For example, the MD5 hash of ‘bytefreaks.net’ (without the quotes) should be 16c00d9cfaef1688d4f2ddfb11b60f46 but if you execute the following you will see you will get a different result.
echo 'bytefreaks.net' | md5sum
01c46835dcb79be359e0b464ae6c6156 -

To avoid this error, use the -n option for echo that will direct the command not to output a trailing new line character.
echo -n 'bytefreaks.net' | md5sum
16c00d9cfaef1688d4f2ddfb11b60f46 -