2012-07-26 49 views
0

下面我有一个文件中的一些什么样的这个如何做的grep在UNIX或AWK

开始--- abcxyz

末---- efg123

参考---- 2345

松弛---- lmnop

..... ...... 和上面的格式与其他的事情重复一次之间的“开始& Slack“

我想grep文件中的行为”开始“”结束“”松弛“ 那么我们如何才能在unix或AWK中做到这一点。

-Thanks

回答

1

据我了解你的问题......你可以试试这个

INPUTFILE

Start ---abcxyz 

End ---- efg123 

Ref ----2345 

Slack---- lmnop 

Some other text 

Some other text 

Some other text 

Start ---osdidiu 

End ---- llll 

Ref ----234513 

Slack---- lmnodsasdp 

代码

awk '$1 == "Start" || $1 == "End" || $1 == "Slack----" {print $0}' InputFile 

输出

Start ---abcxyz 
End ---- efg123 
Slack---- lmnop 
Start ---osdidiu 
End ---- llll 
Slack---- lmnodsasdp 
7

我可以用两种不同的方式看这个问题,两个标记或只是输出多种类型的线之间要么呼应线。


如果希望线End(例如),则可以使用awk具有 “回声” 变量之间Start

echo 'Start ---abcxyz 
something goes here 
and here 
End ---- efg123 
Ref ----2345 
Slack---- lmnop' | awk ' 
    /^Start/{ e = 1 } 
       { if (e) { print } } 
    /^End/ { e = 0 } 
    ' 

输出是:

Start ---abcxyz 
something goes here 
and here 
End ---- efg123 

回声变量e最初未设置,因此if状态恩将永远不会开火。只要awk看到一行以Start开头的行,就会将echo变量设置为true。在这种情况下,所有的线路都会从这一点回应。

然后,当awk看到一条以End开头的行时,它会将echo标志设置回false,以防止进一步输出。

三条命令的顺序可以用来决定是否打印开始和结束行。例如,如果你不想让他们,你可以交换第一和第三个命令(在开始和结束的):

echo 'Start ---abcxyz 
something goes here 
and here 
End ---- efg123 
Ref ----2345 
Slack---- lmnop' | awk ' 
    /^End/ { e = 0 } 
       { if (e) { print } } 
    /^Start/{ e = 1 } 
    ' 

输出是:

something goes here 
and here 

如果你只是要的开始,结束和松弛索,grep相当capabale这样做的:

echo 'Start ---abcxyz 
something goes here 
and here 
End ---- efg123 
Ref ----2345 
Slack---- lmnop' | egrep '^Start |^End |^Slack' 

输出是:

Start ---abcxyz 
End ---- efg123 
Slack---- lmnop