Venturing Forth

toolbox-linux

Print text file without comments and empty lines

When printing long text files, especially configuration files it is somehow useful to clean a little the output avoiding useless blank lines and comments of any sort.
Some files use the double slash, some other a C style /* … */ comments and most common configuration files use the # character to mark comments to their respective parsers.

If you are debugging, or just testing some changes on your system, you may benefit of a thinner video output, especially if this allows you to have the whole content in one only video screen.

There are several ways to do that as almost every GNU/Linux text manipulation tool is equipped with so many options that the same result can be obtained in a variety of ways.

I prepared some snippets to enclose these commands in a simple function with a handy name to get this features available in Bash.

Append the following lines into your .bashrc file or in you ~/.bash_profile

cc  (clean cat)

to remove from a file all the empty lines and the lines starting with spaces and then a comment. If there is some real content the line is printed to the standard output.

function cc {
            cat $1 | egrep -v "(^[[:space:]]*#.*|^$)"
} 

cc command expects one parameter containing the file name you want to print. 

ccn (clean cat with line numbering)

to print the same lines as above with the line number on the top left column.

Also in this case the first (and only) parameter expected is the file name.

function ccn {
           cat -n $1 | egrep -v "(^[[:space:]]*#.*|^$)"
} 

Cctrim (clean cat and pad left)

Thie version is a cc with all text aligned to the left, so with all initial spaces removed.

Also cctrim expects the file name as only parameter.

function cctrim {
            sed 's/^[[:blank:]]*//;s/[[:blank:]]*$//' < $1 | egrep -v "(^#.*|^$)"
} 

One note on the parameter: you can feed cat with more options to the cat part of the command just prepending them before the file name and quoting the whole glob, like in

cc “-tnAvb filetoprint.conf”

this should work in almost all cases and such options will be passed to underlying cat command.

 

Hope this will ease your life in analyzing your etc directory!

Please send me comments if you improve these snippets and feel free to subscribe if you want to be updated on any progress of mine on it!

Auf wiederluoege

Alex

Leave a Comment

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