2

Let's say the lines in words.txt look like this, for example:

Cute Stack 10

Dog Fire 384

Phone Real 485

I want to check if the middle text in each line (stack, fire, real) is equal to a certain input by the user, and if it is, then to print that entire line.

2
  • 2
    seems offtopic for VIM, better moved to SO!?!
    – flowtron
    Commented Dec 22, 2017 at 11:40
  • 2
    I'm voting to close this question as off-topic because it's a programming question, not a question about vi/vim.
    – Herb
    Commented Dec 22, 2017 at 16:31

1 Answer 1

1

In your example, each line has three words in it, with the last "word" also being an integer - but if we read those lines in, they will be of the string-type persuasion; so we'd have to cast that last word to do arithmetic with it. Which is not part of your question, just to clarify what the code below will be doing and not doing.

We will use the split function that the string library provides to look for (hence the variable is named 'look' - nomen est omen) the string "Fire" - imagine this as being passed in as your user input you mentioned. Then we assume we got the text (variable named 'text') from somewhere with the three lines in it you posted as example. Of course the "\n"-bit of the string is the escape sequence for a newline-character.

This is also the argument we pass to the split function, which - nomen es omen - splits up our string at each occurrence of the passed in delimiter, meaning any newline characters. The result is an array with each line as an element in it.

We then loop over these, use split again to separate the words - here I used a space, you might want to use a TAB ("\t").

We check there are 3 words in the result of that split and whether or not the second word (index: 0, 1, 2 for the three elements) is equal to the string we are looking for … if so: you have reached your goal

from string import split
look = "Fire"
text = "Cute Stack 10\nDog Fire 384\nPhone Real 485\n"
list = text.split("\n")
for line in list:
    words = list.split(" ")
    if( len(words) == 3 && words[1] == look ):
        print line
1
  • Welcome on the StackExchange :-) Note, natural language answers are typically better welcomed.
    – peterh
    Commented Dec 22, 2017 at 20:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.