anish
anish

Reputation: 7422

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

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

Answers (5)

potong
potong

Reputation: 58578

This might work for you (GNU sed);

 sed '/^[^#]/,$!b;/^#/d' file

Upvotes: 0

andrewdotn
andrewdotn

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

glenn jackman
glenn jackman

Reputation: 247220

With GNU sed, you have

sed '3,${/^#/d}' 

Upvotes: 1

gpojd
gpojd

Reputation: 23085

You can try awk:

awk 'NR==1 || NR==2 || !/^#/' file.txt

Upvotes: 4

Adam Sznajder
Adam Sznajder

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

Related Questions