Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove "#" comment lines from the middle of a file

Tags:

bash

shell

I want remove comment lines, beginning with "#", from the middle of a file, without removing header comment lines at the top of the file. How can I do this using shell scripts and standard Unix tools?

#DO NOT MODIFY THIS FILE.
#Mon Jan 14 22:25:16 PST 2013
/test/v1=1.0
#PROPERTIES P1.   <------REMOVE THIS 
/test/p1=1.0
/test/p2=1.0
/test/p3=3.0
/test/p41=4.0
/test/v6=1.0
#. P2 PROPERTIES   <------REMOVE THIS
/test/p1=1.0
/test/p2=1.0
/test/p3=3.0
/test/p41=4.0
/test/v6=1.0
.................
.................

Output

#DO NOT MODIFY THIS FILE.
#Mon Jan 14 22:25:16 PST 2013
/test/v1=1.0
/test/p1=1.0
/test/p2=1.0
/test/p3=3.0
/test/p41=4.0
/test/v6=1.0
/test/p1=1.0
/test/p2=1.0
/test/p3=3.0
/test/p41=4.0
/test/v6=1.0
.................
.................
like image 832
anish Avatar asked Nov 19 '25 01:11

anish


2 Answers

You can try awk:

awk 'NR==1 || NR==2 || !/^#/' file.txt
like image 78
gpojd Avatar answered Nov 22 '25 00:11

gpojd


If you don't want to use awk:

head -n 2 file.txt > output.txt
grep -v "^#.*" file.txt >> output.txt
like image 22
Adam Sznajder Avatar answered Nov 21 '25 23:11

Adam Sznajder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!