2013-01-17 130 views
1

我想從文件中間刪除以「#」開頭的註釋行,而不刪除文件頂部的標題註釋行。我怎樣才能使用shell腳本和標準的Unix工具來做到這一點?刪除文件中間的「#」註釋行

#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 
................. 
................. 

輸出

#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 
................. 
................. 
+1

你在問如何修改一個文件「不要修改這個文件」。在頂部? –

+0

我試過使用sed的問題是,我無法刪除該文件之間的評論,所有都被刪除,我嘗試保持第一個評論,並休息所有評論應該被忽略不能,因爲我不會去的 – anish

+0

我要去第二個評論上面。你不應該修改那個文件。 – thang

回答

3

您可以嘗試awk

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

就像一個魅力一樣工作 – anish

2

如果你不想用awk:

head -n 2 file.txt > output.txt 
grep -v "^#.*" file.txt >> output.txt 
+3

你可以這樣做:'{head -n 2 file.txt; grep -v'^#'file.txt; }> output.txt' –

1

你想呼應線以'#'開頭,但僅限於一開始只使用bash?從布爾值start=true開始;然後逐行進行,當線路不以#開始時,設置爲start=false,並且僅當您處於起點或線路不以#開頭時纔回顯每條線路。

這裏的文件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 

運行它:

$ 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 
+1

爲什麼選擇在子shell中運行while循環? –

+0

好點 - 這沒有什麼好的理由。我修復了它。謝謝! – andrewdotn

1

隨着GNU sed的,你有

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

這可能會爲你(GNU SED)的工作;

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

你是否錯過了正則表達式的結束斜槓? –

+0

@glennjackman哎呀!謝謝。 – potong