繁体   English   中英

跳到txt文件中的特定行

[英]Jump on specific line in txt file

我有一个大文本文件,我想打开它并跳到包含特定字符串的行上。 我设法做的是跳到特定的行号上。

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

如何编辑代码,以便它搜索特定的字符串而不是行号?

您可以在下一行作为您要查找的文本的第一个出现位置来调用该行:

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

这个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 ':'表示:

  1. grep ...告诉我所有有“ test_to_find”和带有行号前缀的行
  2. head ... :第一次出现
  3. cut ...获取行号

如果没有出现,您必须修复它

您真的无法打开文件并直接跳到一行,而无需先做一些逻辑判断该行的位置。

这应该可以解决问题:

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

您可能还需要看一下: https : //docs.python.org/2/library/linecache.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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