Reputation: 7422
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
.................
.................
Upvotes: 2
Views: 2402
Reputation: 34883
You want to echo the lines beginning with '#', but only at the beginning, using only bash? Start with a boolean start=true
; then go line-by-line, set start=false
when the line doesn’t start with #
, and echo each line only if you are at the start or the line does not start with #
.
Here’s the file script
:
#!/bin/bash
start=true
while read line; do
if $start; then
if [ "${line:0:1}" != "#" ]; then
start=false
fi
fi
if $start || [ "${line:0:1}" != "#" ]; then
echo "${line}"
fi
done
Running it:
$ cat input
#DO NOT MODIFY THIS FILE.
#Mon Jan 14 22:25:16 PST 2013
/test/v1=1.0
#PROPERTIES P1.
/test/p1=1.0
/test/p2=1.0
/test/p3=3.0
/test/p41=4.0
/test/v6=1.0
#. P2 PROPERTIES
/test/p1=1.0
/test/p2=1.0
/test/p3=3.0
/test/p41=4.0
/test/v6=1.0
$ ./script < input
#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
Upvotes: 1
Reputation: 9216
If you don't want to use awk:
head -n 2 file.txt > output.txt
grep -v "^#.*" file.txt >> output.txt
Upvotes: 3