bash 使用 sed 删除两个模式(不包括)之间的线条
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5071901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
removing lines between two patterns (not inclusive) with sed
提问by kasper
Ok
好的
I know that this is trivial question but: How can i remove lines from files that are between two known patterns/words:
我知道这是一个微不足道的问题,但是:如何从两个已知模式/单词之间的文件中删除行:
pattern1
garbage
pattern2
模式 1
垃圾
模式 2
to obtain:
获得:
pattern1
pattern2
模式1
模式2
And does anyone known good(simple written!) resources for studying sed?? With many clear examples?
有没有人知道学习 sed 的好(简单写!)资源?有很多清楚的例子吗?
回答by Paused until further notice.
sed -n '/pattern1/{p; :a; N; /pattern2/!ba; s/.*\n//}; p' inputfile
Explanation:
解释:
/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)
Edit:
编辑:
Some versions of sedhave to be spoon-fed:
某些版本sed必须用勺子喂食:
sed -n -e '/pattern1/{' -e 'p' -e ':a' -e 'N' -e '/pattern2/!ba' -e 's/.*\n//' -e '}' -e 'p' inputfile
回答by potong
This might work for you:
这可能对你有用:
sed '/pattern1/,/pattern2/{//!d}' file
回答by Daniel Gallagher
This is easily done with awk:
这很容易用 awk 完成:
BEGIN { doPrint = 1; }
/pattern1/ { doPrint = 0; print awk '/pattern1/{g=1;next}/pattern2/{g=0;next}g' file
; }
/pattern2/ { doPrint = 1; }
{ if (doPrint) print sed '/PATTERN1/,/PATTERN2/d' FILE
; }
I've found the sed infois fairly easy reading, with many examples. Same thing for awk.
回答by kurumi
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
回答by publkaccion
This sed code will work as well:
这个 sed 代码也可以工作:
##代码##回答by tylo
You may also use the Unix text editor ed:
你也可以使用 Unix 文本编辑器 ed:
##代码##For more information see: Editing files with the ed text editor from scripts
有关更多信息,请参阅:使用 ed 文本编辑器从脚本编辑文件

