文件内容如下(file.conf):
/etc/:
rc.conf
passwd
/usr/:
/usr/local/etc/:
我需要在“/ etc /:”和第一个匹配的行之间选择行,并在末尾添加“:”。
cat ./file.conf | sed -n '/\/etc\/:/,/\/.*:$/p'
打印所有内容,但我需要
/etc/:
rc.conf
passwd
/usr/:
使用此命令cat ./file.conf | sed -n '/\/etc\/:/,/\/.*:$/p; :q'
相同。
答案 0 :(得分: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
答案 1 :(得分:1)
您可以试试sed
:
sed -n '/\/etc\/:/{:loop; $q; $!N; /:/b p; b loop; }; :p; p' file.conf
<强>输出:强>
/etc/:
rc.conf
passwd
/usr/: