Friday, February 4, 2011

grep and columns in color!

I really wanted my dictionary searches to output in columns, but without loosing grep's color.  The problem is that if you use the --color=always option in grep it distorts the length of the strings in the pipeline because of the escape sequences used for coloring in the terminal.  Then when you pipe the results into column the columns do not look right.

Never fear.  awk is here.  I wrote this tiny script to append spaces to each line so they all had at least length 35.

Here's normalize.awk
#!/usr/bin/gawk -f

{
    str = $1
    difference = 35 - length($1);
    while(difference > 0)
    {
        str = str " "
        difference--
    }
    print str
}

and here's the finished command:

grep --color=always st$ dict | ./normalize.awk | column

This command found all the words in the dictionary ending in "st" and displays them in columns with the "st" portion highlighted.

No comments:

Post a Comment