Stripping leading whitespace and comments with sed

In trying to consolidate some bash aliases (found in .bashrc and .bash_aliases), I needed to strip out comments and leading whitespace to sort for unique lines.

To strip spaces, I used
egrep alias .bashrc | sed 's/^[ ]*//'

To remove spaces and tabs in the whitespace (see info on tabs after this example):
egrep alias .bashrc | sed 's/^[ ]*//'
NOTE: In the expression, sed 's/^[ ]*//' , the expression in the brackets is actually a space followed by a tab. At the command line, I had to create the tab by typing Control-V and then hitting TAB on the keyboard. You may need to represent tabs in a different fashion.

To get rid of leading whitespace, comments, and indented comments, I settled on
egrep alias .bashrc | sed 's/^[ ]*//' | egrep -v '^#'

To gather and sort aliases from both .bash and .bash_aliases, then sending to a temporary file:
egrep -h alias .bash[r_][ca]* | sed 's/^[ ]*//' | egrep -v '^#' | sort -u >> tmp

The -h flag tells the first grep not to print the file name.

Tags: , ,

Leave a Reply

You must be logged in to post a comment.