2013-10-23 19 views
0

有下面內容(file.conf)的文件是「的/ etc /:」和首尾匹配帶「:」的行。選擇線

cat ./file.conf | sed -n '/\/etc\/:/,/\/.*:$/p' 

打印所有內容,但我需要

/etc/: 
rc.conf 
passwd 
/usr/: 

使用此命令cat ./file.conf | sed -n '/\/etc\/:/,/\/.*:$/p; :q'相同。

+0

貓是沒用的:'sed的-n '/\/etc\/:/,/\/.*:$/p' file.conf'的[ –

+0

可能重複的兩個關鍵字內複製節成目標文件](http://stackoverflow.com/questions/19434755/copy-a-section-within-two-keywords-into-a-target-file) – Bentoy13

+0

不,這不重複。 – Andry

回答

1

awk解決方案

awk '/^\/etc\// {f=1} f; /:$/ && !/\/etc\//{f=0}' file.conf 
/etc/: 
rc.conf 
passwd 
/usr/: 

另一個版本

awk '/^\/etc\// {f=1;print;next} f; /:$/ {f=0}' file.conf 

awk ' 
    /^\/etc\// { # search for /etc/, if found do 
     f=1   # set flag f=1 
     print  # print this line (/etc/ line) 
     next  # skip to next line so this would not be printed twice 
     } 
    f;    # Is flag f set, yes do default action { print $0 } 
    /:$/ {   # does line end with : 
     f=0   # yes, reset flag 
     } 
    ' file.conf 
+0

是的,它的工作。謝謝!但對我而言,sed有可能嗎?可能是這樣的:{2} q在最後一個sed命令中...... – Andry

+0

當然可以用'sed''。您可能必須使用條件分支。 – steffen

+0

使用awk的解決方案適合我,但需要一些幫助。上次命令中的「{f = 1; print; next} f」是什麼意思? – Andry

1

你可以試試這個sed

sed -n '/\/etc\/:/{:loop; $q; $!N; /:/b p; b loop; }; :p; p' file.conf 

輸出:

/etc/: 
rc.conf 
passwd 
/usr/: 
+0

在我的Ubuntu上,這給了我不想要的最後一行。 '/ usr/local/etc /:' – Jotne

+0

現在好像沒問題:) – Jotne

+0

在我的FreeBSD sed:1上:「/ \/etc \ /:/ {:loop; $ q; $ ...」:意外的EOF(pending)') – Andry