[英]bash, sed, awk: extracting lines within a range
How can I get sed to extract the lines between two patterns, write that data to a file, and then extract the lines between the next range and write that text to another file?如何让 sed 提取两个模式之间的行,将该数据写入文件,然后提取下一个范围之间的行并将该文本写入另一个文件? For example given the following input:
例如,给定以下输入:
pattern_a
line1
line2
line3
pattern_b
pattern_a
line4
line5
line6
pattern_b
I want line1 line2 and line3 to appear in one file and line4 line5 and line6 to appear in another file.我希望 line1 line2 和 line3 出现在一个文件中,而 line4 line5 和 line6 出现在另一个文件中。 I can't see a way of doing this without using a loop and maintaining some state between iterations of the loop where the state tells you where sed must start start search to looking for the start pattern (pattern_a) again.
如果不使用循环并在循环的迭代之间维护一些 state,我看不到这样做的方法,其中 state 告诉您 sed_ 必须开始搜索的位置再次开始搜索。
For example, in bash-like psuedocode:例如,在类似 bash 的伪代码中:
while not done
if [[ first ]]; then
sed -n -e '/pattern_a/,/pattern_b/p' > $filename
else
sed -n -e '$linenumber,/pattern_b/p' > $filename
fi
linenumber = last_matched_line
filename = new_filename
Is there a nifty way of doing this using sed?有没有使用 sed 的绝妙方法? Or would awk be better?
还是 awk 会更好?
How about this:这个怎么样:
awk '/pattern_a/{f=1;c+=1;next}/pattern_b/{f=0;next}f{print > "outfile_"c}' input_file
This will create a outfile_x
for every range.这将为每个范围创建一个
outfile_x
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.