【发布时间】:2010-07-21 00:16:41
【问题描述】:
我有几个文本文件,它们曾经是数据库中的表,现在已被反汇编。我正在尝试重新组装它们,一旦我将它们变成可用的形式,这将很容易。第一个文件“keys.text”只是一个标签列表,格式不一致。喜欢:
Sa 1 #
Sa 2
U 328 #*
它总是字母、[空格]、数字、[空格],有时还有符号。与这些键匹配的文本文件是相同的,然后是一行文本,也由空格分隔或定界。
Sa 1 # Random line of text follows.
Sa 2 This text is just as random.
U 328 #* Continuing text...
我在下面的代码中尝试做的是将“keys.text”中的键与 .txt 文件中的相同键匹配,并在键和文本之间放置一个制表符。我确定我忽略了一些非常基本的东西,但我得到的结果看起来与源 .txt 文件相同。
提前感谢任何线索或帮助!
#!/usr/bin/perl
use strict;
use warnings;
use diagnostics;
open(IN1, "keys.text");
my $key;
# Read each line one at a time
while ($key = <IN1>) {
# For each txt file in the current directory
foreach my $file (<*.txt>) {
open(IN, $file) or die("Cannot open TXT file for reading: $!");
open(OUT, ">temp.txt") or die("Cannot open output file: $!");
# Add temp modified file into directory
my $newFilename = "modified\/keyed_" . $file;
my $line;
# Read each line one at a time
while ($line = <IN>) {
$line =~ s/"\$key"/"\$key" . "\/t"/;
print(OUT "$line");
}
rename("temp.txt", "$newFilename");
}
}
编辑:澄清一下,如果有的话,结果也应该保留键中的符号。所以它们看起来像:
Sa 1 # Random line of text follows.
Sa 2 This text is just as random.
U 328 #* Continuing text...
【问题讨论】:
-
我猜您的输出与您的输入相同,因为您的正则表达式不匹配任何内容。查看下面的 cHao 的答案来解决这个问题。如果您知道每个“数据”文件都将以密钥开头,那么您就不能在不知道密钥的情况下将标签推入吗?密钥将始终匹配 /\w+\s\w+\s[*|#]*/ 或 [*|#] 中的任何其他内容?
标签: perl variables substitution