开发者

Is there a way to put the following logic into a grep command?

For example suppose I have the following piece of data

ABC,3,4
,,ExtraInfo
,,MoreInfo
XYZ,6,7
,,XyzInfo
,,MoreXyz
ABC,1,2
,,ABCInfo
,,MoreABC

It's trivial to get grep to extract the ABC lines. However if I want to also grab the following lines to produce this output

ABC,3,4
,,ExtraInfo
,,MoreInfo
ABC,1,2
,,ABCInfo
,,MoreABC

Can this be done using grep and standard shell scripting?

Edit: Just to clarify there could be a variable number of line开发者_高级运维s in between. The logic would be to keep printing while the first column of the CSV is empty.


grep -A 2 {Your regex} will output the two lines following the found strings.

Update: Since you specified that it could be any number of lines, this would not be possible as grep focuses on matching on a single line see the following questions:

  • How can I search for a multiline pattern in a file?
  • Regex (grep) for multi-line search needed
  • Why can't i match the pattern in this case?
  • Selecting text spanning multiple lines using grep and regular expressions


You can use this, although a bit hackity due to the grep at the end of the pipeline to mute out anything that does not start with 'A' or ',':

$ sed -n '/^ABC/,/^[^,]/p' yourfile.txt| grep -v '^[^A,]'

Edit: A less hackity way is to use awk:

$ awk '/^ABC/ { want = 1 } !/^ABC/ && !/^,/ { want = 0 } { if (want) print }' f.txt

You can understand what it does if you read out loud the pattern and the thing in the braces.


The manpage has explanations for the options, of which you want to look at -A under Context Line Control.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜