大网数据广告活动
服务器运维问答

Grep by block of text\lines

· 52CE 我爱测

I have the text, that contains some lines. So, i need to make GREP of several lines. For example, i have repeating text and i should GREP get lines, that have this repeating key-words. grep -o "test|test2" textfile My text: 123|n…

问题原文

原帖链接 · Valeriu · CC BY-SA 3.0

I have the text, that contains some lines. So, i need to make GREP of several lines. For example, i have repeating text and i should GREP get lines, that have this repeating key-words.

grep -o "test|test2" textfile

My text:

123|never for your|test
123421|never for your|test2
123412|never for your|test3
12341|never for your|test4
12311|never for your|test2
123312312|never for your|test
123321312|never for your|test2

I should have:

123|never for your|test
123421|never for your|test2
123312312|never for your|test
123321312|never for your|test2

It works, but it doesn't work how i want. It searchs in text, all words "test" & "test2". But i want to get textblocks, like some pattern, where only after "test" comes "test2". Have you got any ideas ?

已采纳解答

原帖链接 · Chris Rees · CC BY-SA 3.0

Brief shell script using sed. Makes a list of line numbers for the second case, and compares against line numbers for the first case. Prints matching pairs. Uses the first argument as the file name. Could easily be extended to take second and third arguments as patterns to match. Could save as findnext.sh, and run:

$ sh findnext.sh testfile

Should be quick as it only involves two passes over the file, and has the advantage of being completely portable.

#!/bin/sh 
# Line numbers matching test1
mt2=$(sed -ne '/test1/=' < $1 | tr '\n' '/')

for l in $(sed -ne '/test/=' < $1); do
    nextline=$(expr $l + 1)
    [ "${mt2#*$nextline/}" != "$mt2" ] && sed -ne $l,${nextline}p <$1
done

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-01-21)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。