[英]removing lines between two patterns (not inclusive) with sed
Ok行
I know that this is trivial question but: How can i remove lines from files that are between two known patterns/words:我知道这是一个微不足道的问题,但是:如何从两个已知模式/单词之间的文件中删除行:
pattern1
模式1
garbage垃圾
pattern2模式2
to obtain:获得:
pattern1
模式1
pattern2模式2
And does anyone known good(simple written!) resources for studying sed??有没有人知道学习 sed 的好(简单的书面!)资源? With many clear examples?
有很多明确的例子吗?
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 sed
have 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
这可能对你有用:
sed '/pattern1/,/pattern2/{//!d}' file
awk '/pattern1/{g=1;next}/pattern2/{g=0;next}g' file
这个sed代码也可以运行:
sed '/PATTERN1/,/PATTERN2/d' FILE
You may also use the Unix text editor ed: 您也可以使用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
For more information see: Editing files with the ed text editor from scripts 有关更多信息,请参阅: 使用脚本中的ed文本编辑器编辑文件
for me "sed '\/PATTERN1\/,\/PATTERN2\/d' FILE" is working (between PATTERN1 and last occurrence of PATTERN2)对我来说,“sed '\/PATTERN1\/,\/PATTERN2\/d' FILE”正在工作(在 PATTERN1 和最后一次出现的 PATTERN2 之间)
but i have a question: if PATTERN2 has multi occurrence, how can I make it working until first occurrence of PATTERN2, not last one?但我有一个问题:如果 PATTERN2 多次出现,我怎样才能让它工作直到第一次出现 PATTERN2,而不是最后一次?
Thanks谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.