简体   繁体   中英

Jump on specific line in txt file

I have a big text file and I want to open it and jump on a line that contains a specific string. What I managed to do is jump on a specific line number.

import os
os.system('sudo gedit +50 test.txt')

How can i edit the code so that it searches for a specific string instead of a line number?

You can invoke the line as first ocurrence of text that are you looking for with next line:

   gedit +$(grep -n "id" test.txt  | head -n 1 | cut -f 1 -d ':')  test.txt

This grep -n "text_to_find" test.txt | head -n 1 | cut -f 1 -d ':' grep -n "text_to_find" test.txt | head -n 1 | cut -f 1 -d ':' grep -n "text_to_find" test.txt | head -n 1 | cut -f 1 -d ':' means:

  1. grep ... Tell me all lines where there are "test_to_find" and prefix with line number
  2. head ... : get first occurrence
  3. cut ... get the line number

You have to fix it in case that there are not ocurrences

You're not really going to be able to open the file and jump straight to a line, without first doing some logic to figure where that line is.

This should do the trick:

with open('test.txt', 'r') as myFile:
    for line in myFile:
        if 'My Search String Here' in line:
            print line

You may also want to look at this: https://docs.python.org/2/library/linecache.html

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