【发布时间】:2011-02-21 22:18:14
【问题描述】:
好的
我知道这是一个微不足道的问题,但是:如何从两个已知模式/单词之间的文件中删除行:
模式1
垃圾
模式2
获得:
模式1
模式2
有没有人知道学习 sed 的好(简单写!)资源?有很多明确的例子吗?
【问题讨论】:
好的
我知道这是一个微不足道的问题,但是:如何从两个已知模式/单词之间的文件中删除行:
模式1
垃圾
模式2
获得:
模式1
模式2
有没有人知道学习 sed 的好(简单写!)资源?有很多明确的例子吗?
【问题讨论】:
这可能对你有用:
sed '/pattern1/,/pattern2/{//!d}' file
【讨论】:
sed(即 Mac OSX)一起使用,并且您收到错误 extra characters at the end of d command,只需在 d 之后添加 ;,如下所示:sed '/pattern1/,/pattern2/{//!d;}' file
sed -n '/pattern1/{p; :a; N; /pattern2/!ba; s/.*\n//}; p' inputfile
解释:
/pattern1/{ # if pattern1 is found
p # print it
:a # loop
N # and accumulate lines
/pattern2/!ba # until pattern2 is found
s/.*\n// # delete the part before pattern2
}
p # print the line (it's either pattern2 or it's outside the block)
编辑:
sed 的某些版本必须用勺子喂:
sed -n -e '/pattern1/{' -e 'p' -e ':a' -e 'N' -e '/pattern2/!ba' -e 's/.*\n//' -e '}' -e 'p' inputfile
【讨论】:
sed: -e expression #1, char 58: Unknown option to 's'。我的 sed 版本是 3.02
sed '/pattern1/,/pattern2/{/pattern1/b;/pattern2/b;d}' inputfile :)
echo -e 'aaa\npattern1\ncccxxx\ndddxxx \npattern2\nfff\nggg\npattern1\nAAAxxx\nBBBxxx \nCCCxxx\nDDDxxx\npattern2\nEEE\nFFF'
awk '/pattern1/{g=1;next}/pattern2/{g=0;next}g' file
【讨论】:
这个 sed 代码也可以工作:
sed '/PATTERN1/,/PATTERN2/d' FILE
【讨论】:
您也可以使用 Unix 文本编辑器编辑:
echo '
pattern1
garbage
pattern2
' > test.txt
cat <<-'EOF' | sed -e 's/^ *//' -e 's/ *$//' | ed -s test.txt &>/dev/null
H
/pattern1/+1,/pattern2/-1d
wq
EOF
欲了解更多信息,请参阅:Editing files with the ed text editor from scripts
【讨论】: