Ignore Lines Begining With #

Is there a standard way to make a shell script read a file, or list, and skip each line that contains # at the begining, or ignores the content starting after a # in line?

I'm looking to mimic the way commenting in a shell script normally works. This way I can comment my text files and lists my scripts process and ignore comment lines.

Thanks guys. :slight_smile:

If you want to do only a couple things with the output, filter you source file in a pipeline:

grep -v '^[[:space:]]*#' /path/to/your/file | your_commands

if you want do extensive stuff with your comment-stripped file, save the stripped file in a temp file, and use use the temp file for the rest of the procedure:

grep -v '^[[:space:]]*#' /path/to/your/file  >/tmp/stripped_source

Note that I use ^[[:space:]]* at the start of the regular expression because lines that are completely comments can still contain leading whitespace. If you want to eliminate blank lines also, do

 egrep -v '(^[[:space:]]*#|^[[:space:]]*$)' /path/to/file >/tmp/stripped_file

Try...

$ cat file1
#line1
  #line2
line#3
line4

$ sed '/^ *#/d;s/#.*//' file1
line
line4

After some testing I went with this method. Thanks to both of you. :slight_smile:

If you want your script to behave like the ksh itself (ignore the part of a line after a "#" but use the part before it) you could do the following (replace "<spc>" with a literal space, "<tab>" with a tab char):

script

sed 's/#.*$/;s/^[<spc><tab>]*//;s/[<spc><tab>]*$//;/^$/d' file

content of file
# this is a line with comments
   # this too, but starting with blanks
command 1        # this line contains an inline comment

command 2 "#"   # this too, but my script would be confused

result
command 1
command 2 "

Alas, the script fails on the second line, but save for such delicacies it works.

bakunin