1

I have a program that I could run by feeding it some instructions from an input file by redirection. My input file looks like this:

alpha
5
2
run
7
quit

Now, I run it like this:

myprogram < input_file

However, sometimes I need to add some comments to the input file to make it clear, e.g

# The name of value
alpha
# The acceleration
5
# The distance 
2
run
7
quit

Unfortunately, now I can't redirect it to the program because It will not ignore the lines starting with #

How can I ignore those comment lines before redirecting it to myprgram?

2 Answers 2

2

You can use grep to filter out lines beginning with "#":

grep -v '^#' input_file | myprogram

The string passed to grep is a regular expression. It matches the beginning of the line (^) followed by #. -v inverts the logic so it shows lines NOT matching this pattern.

Generally I would choose grep to simply show/discard whole lines and sed if I wanted to modify data within lines. But of course the sed solution works as well.

1

Use sed to filter out lines with comments before giving it to your program. You could choose one of those forms (but the second, process substitution, is not supported by all shells):

sed '/^#/d' input_file | myprogram
myprogram < <(sed '/^#/d' input_file)

/^#/ is the regex that matches any line that begins with #, d is the command to delete those lines from the output. (Do not worry, input_file won't be modified by sed).

0

You must log in to answer this question.