2013-02-22 69 views
4

我正在嘗試使用sed取消註釋此配置文件中的一段文本。 代碼我想出了從第一場比賽開始的取消註釋7行,包括第一場比賽的模式匹配,但我需要它只在第二場比賽中工作,並跳過第一場比賽。如何使用sed取消第二模式匹配的多行註釋?

    sed '/#location.~.*$/,+6s/#/ /' default.conf 

# proxy the PHP scripts to Apache listening on 127.0.0.1:80 
# 
#location ~ \.php$ { 
# proxy_pass http://127.0.0.1; 
#} 

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 
# 
#location ~ \.php$ {     
# root   html; 
# fastcgi_pass 127.0.0.1:9000; 
# fastcgi_index index.php; 
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; 
# include  fastcgi_params; 
#} 
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 
# 

>

回答

3

這可能爲你工作(GNU SED):

sed 'x;/./{x;/#location/,+6s/#/ /;b};x;/#location/h' file 

使用的保留空間(HS)來存儲的地址範圍內的標誌,只有行爲如果標誌已設置。

+0

哇..我只是試過這個,它工作得很好。 – 2013-02-23 01:11:18

+0

我的意思是說謝謝,你爲我節省了很多時間 – 2013-02-23 05:05:16

+0

這是神奇的!感謝教我更多關於SED :) – codekoala 2013-08-15 21:14:42

0

隨着(這是更合適的比sed &更容易完成這個任務):

awk -F# ' 
    /^#location/{l++} 
    l<2 {print} 
    l==2{print $2} 
    l==2 && $2 ~ "}" {l=0;next} 
' file.txt 
+0

感謝隊友,我無法按原樣工作,我一定做錯了什麼。雖然我感謝你的幫助。 – 2013-02-23 05:07:37

1

我會說,使用shell腳本來改變你的代碼是有風險的。許多特例可能會導致失敗。

我將其稱爲「文本轉換」。它將從#location ~ \.php$ {行刪除前導#行到第一個#}行。

AWK onliner:

awk '/^#location ~/{s=1}s{if($0~/^#}/)s=0;sub("#"," ")}1' file 

見例如:(文件內容)

kent$ awk '/^#location ~/{s=1}s{if($0~/^#}/)s=0;sub("#"," ")}1' file 
# proxy the PHP scripts to Apache listening on 127.0.0.1:80 
# 
location ~ \.php$ { 
    proxy_pass http://127.0.0.1; 
} 

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 
# 
location ~ \.php$ {     
    root   html; 
    fastcgi_pass 127.0.0.1:9000; 
    fastcgi_index index.php; 
    fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; 
    include  fastcgi_params; 
} 
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 
# 

我希望上面的輸出是你需要的。

+0

非常感謝,但我需要第一場比賽被忽略,我沒有任何經驗與awk玩和修改它 – 2013-02-23 01:14:27