简体   繁体   English

Perl:如何逐行搜索文本文件以查找特定模式?

[英]Perl: How do I search a text file line by line to find a specific pattern?

I want to find a string STRING at the beginning of each line of a text file. 我想在文本文件每一行的开头找到一个字符串STRING So far, I have: 到目前为止,我有:

open(FILEHANDLE, "sample.txt")

while(my $line = <$FILEHANDLE>){
    if($line =~ PATTERN){
       doSomething();
    }
}

My question is: what do I put for PATTERN that will make my code work? 我的问题是:我应该为PATTERN放置什么以使代码正常工作? I know that STRING will be at the beginning of each line of the text file, and that STRING will be followed by whitespace. 我知道STRING将会在文本文件每一行的开头,并且STRING后面将是空格。 STRING may change so it must be in a variable and not hardcoded in. STRING可能会更改,因此它必须在变量中且不能进行硬编码。

So far, I can only think of the Python way to do this: 到目前为止,我只能想到使用Python的方式:

PATTERN = r"^" + re.escape(STRING) + r"\s"
if re.search(PATTERN, line):
    doSomething();

How do I translate this to Perl? 如何将其翻译为Perl?

Also, if this is bad Perl syntax, please let me know so I can fix it. 另外,如果这是错误的Perl语法,请告诉我,以便对其进行修复。

You were almost there, just need to know that . 您快要在那里了,只需要知道这一点即可. is string concatenation, not + . 是字符串连接,不是+ and that quotemeta() does string escaping. 并且那个quotemeta()确实进行了字符串转义。

my $pat = "^".quotemeta($string)."\s" ;
while(my $line = <$FILEHANDLE>){
  if($line =~ /$pat/){
    doSomething();
  } 
}

What you're looking for is quotemeta 您正在寻找的是quotemeta

use strict;
use warnings;
use autodie;

my $file = 'sample.txt';
my $literal_string = '...';

open my $fh, '<', $file;

while (my $line = <$fh>){
    if ($line =~ /^\Q$literal_string\E/){
       doSomething();
    }
}

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

相关问题 我需要在文件的标题行中搜索一个模式,并使用Perl连接下一行 - I need search a pattern in a header line of my file and concatenates the next line with Perl 如何在Perl中进行模式匹配之前和之后的行匹配? - How do I match the line before and after a pattern match in Perl? 如何在文本文件中搜索行的内容,替换行并另存为新文件? - How do I search for contents of a line in a text file, replace the line, and save as a new file? 如何在不使用Perl中的正则表达式的情况下在文件中找到特定行? - How can I find a specific line in a file without using regular expressions in Perl? 如何使用Vim或Perl在文件中的特定行上方插入一行? - How do I insert a line above specific lines in a file using Vim or Perl? 搜索模式并替换perl模块文件的整行 - Search a pattern and replace the entire line of a perl module file 如何将 append 文本发送到包含 Perl 中的替换的行? - How do I append text to the line containing a substitution in Perl? 如何使用python在文本文件中查找特定的文本行? - How to find a specific line of text in a text file with python? 如何逐行搜索&#39;/ ## /&#39;的文本文件? - How to search text file line by line for '/##/'? 在Perl中搜索和替换多行模式 - Multiple Line Pattern Search and replace in perl
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM