I find nl very useful tool when working on *nix systems or just any systems. Throwing in number lines on output gives you an idea of where lines start and end. Lines tend to grow long and wrap and without seeing \n chars its impossible to see. Instead of seeing \n. I like number lines.

In linux you can use something like

df -h | nl

or

top -cbn 1 | nl

The nl will give you numbered lines.

But what if your OS doesnt have nl (… FreeBSD… grrr… ehh im sure ill grow to love it eventually)… The solution… awk of course.

So nl  turns into awk ‘{N+=1;print N ”    ” $0;}’

So you get

df -h | awk '{N+=1;print N "    " $0;}'

or

top -cbn 1 | awk '{N+=1; print N "    " $0;}'

Now learn to type those 32 chars as fast as you can type the 2 chars from nl and you will rock!

Anyhow this awk works like this. awk by default reads one line at a time. and each line is processed against the code here {N+=1; print N ”    ” $0;} . We ask a variable N to be incremented by 1 with that N+=1;  (same as N=N+1). So each line read increments N by 1. But wait we didnt initialize or set a starting point for N. Dont worry, awk defaults it to start at 0. So after N+=1. N is 1, which will start our first line (think… line number 1). So then we come across print N ”    ” $0; . This print the line number N followed by some spaces (for pretty separation) followed by the line as it was read ($0). To break it down  print N ”    ” $0;states to print on the screen (stdout print) the variable N followed by 4 spaces followed by a variable $0. For every line processed awk has the following variables $0 (the whole line), $1 (first column of data in a line), $2 (second column of data in a line), and so on… as many times as there are columns (space, tab seperators. We use $0 because we want to print that while line as is.

BONUS – indenting lines with AWK: you can indent by 4 spaces all of your lines like this awk ‘{print ”    ” $0;}’ . Here is an example:

df -h | awk '{print "    " $0;}'

Sorry that no output is provided for any of these. I assume you know how lines that are numbered and indented look like, and the output of top and df are arbitrary/trivial here.

Leave a Reply

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