Danny
Danny

Reputation: 5400

Extracting all lines from a file that are not commented out in a shell script

I'm trying to extract lines from certain files that do not begin with # (commented out). How would I run through a file, ignore everything with a # in front of it, but copy each line that does not start with a # into a different file.

Thanks

Upvotes: 1

Views: 2044

Answers (3)

doomicon
doomicon

Reputation: 11

grep -v ^\# file > newfile
grep -v ^\# file | grep -v ^$ > newfile

Not fancy regex, but I provide this method to Jr. Admins as it helps with understanding of pipes and redirection.

Upvotes: 1

pulsar
pulsar

Reputation: 580

Simpler: grep -v '^[[:space:]]*#' input.txt > output.txt

Upvotes: 4

shellter
shellter

Reputation: 37268

This assumes that you're using Unix/Linux shell and the available Unix toolkit of commands AND that you want to keep a copy of the original file.

cp file file.orig
mv file file.fix
sed '/^[      ]*#/d' file.fix > file
rm file.fix

Or if you've got a nice shiny new GNU sed that all be summarized as

cp file file.orig
sed -i '/^[      ]*#/d' file

In both cases, the regexp in the sed command is meant to be [spaceCharTabChar] So you saying, delete any line that begins with an (optional space or tab chars) #, but print everything else.

I hope this helps.

Upvotes: 1

Related Questions