简体   繁体   中英

Conditional grep/ack searches?

What I mean by this is that I want to search for "thing1", and then I want to search for "thing2" based on the position of the "thing1". And I want to display both of them in the result in the order that they are in the coede.

eg. I find "thing1" on line 100. I want to then search for the first "thing2" that occurs before "thing1". Then I want to display both of these in the order "thing2" then "thing1". I want to do this for every instance of "thing1" that I find.

The reason for this is that I want to search for certain strings which I know will be in lists (python), and I want to know the name of the lists too. So I thought that I could search for the string and then also display the first "= [" sign that occurs before the string.

So if a file has:

my_list = [
    'item1',
    'item2',
    'item3',
]

my_other_list = [
    'item4',
    'item5',
    'item3',
]

and create a search which looks for 'item3' and then to looks back to find the previous '= ['

then the output should be (not including line numbers which grep and ack will put):

my_list = [
    'item3',

my_other_list = [
    'item3',

I think you want this:

awk '/=/{thing2=$0} /item3/{print thing2;print $0,"\n"}' YourFile

So, every time you see an = , you remember the line as thing2 . When you see item3 you print the last thing2 you saw and the current line.

Sample Output

my_list = [
    'item3', 

my_other_list = [
    'item3', 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM