1

我有两个保存 .txt 文件的文件夹。

Folder1 has File1.txt
Folder2 has File2.txt

的内容File1.txt

Some text
    ABCD123X Execute String1
Some text

的内容File2.txt

String1 Procedure
ABCD
EFGH

输出 :

Some text
    ABCD123X Execute String1

    ABCD
    EFGH

Some text

要求 :

如果我在 File2.txt 中'Execute String1'找到模式,我想在 File1.txt 中进行扩展'String1 Procedure'

这是我迄今为止尝试过的:

$string1 = $null
gc $file.fullname | ? {
  if ($_ -match "(.*)EXECUTE(\s)([A-Za-z_0-9][^ |^,]*)" -and $_ -notmatch "^\/\/*") {
    $string1 = $matches[3]
  } elseif ($string1 -ne $null) {
    get-content file.fullname, $string1.fullname | out-file $combined.txt
    # This is appending string1.txt file at end of file.txt
  } 
}

我需要一种将 string1.txt 附加到 file.txt 的方法,而不是在末尾,而是在我找到的位置下方。像这样 :

Some text
ABCD123X Execute String1
ABCD
EFGH
Some text
4

1 回答 1

1

由于File1.txt包含替换字符串列表(我将假设每一行都以标识符词结尾),我建议将它们读入像这样的哈希表:

$replacements = @{};
Get-Content "C:\path\to\File1.txt" | ? { $_ -match '.* (\S+)$' } | % {
  $replacements[$matches[1]] = $matches[0]
}

-match运算符将字符串与正则表达式匹配:

"string" -match 'expression'

结果匹配会自动存储在哈希表中$matches。例子:

PS C:\> "ABCD123X Execute String1" -match '.* (\S+)$'
True
PS C:\> $matches

Name                           Value
----                           -----
1                              String1
0                              ABCD123X Execute String1

这样,您将整个匹配项 ( $matches[0]) 放入哈希表$replacements中,使用第一个子匹配项(正则表达式中括号之间的部分,$matches[1])作为该值的键:

$replacements[$matches[1]] = $matches[0]
       ^          ^              ^
   hashtable     key           value

哈希表基本上是一个字典,您可以在其中按关键字查找短语。例子:

PS C:\> $phonebook = @{
>> "Amy" = "555-1234";
>> "Eve" = "555-6666";
>> "Ivy" = "555-4223";
>> }
>>
PS C:\> $phonebook

Name                           Value
----                           -----
Amy                            555-1234
Eve                            555-6666
Ivy                            555-4223

PS C:\> $phonebook["Mia"] = "555-1327"
PS C:\> $phonebook

Name                           Value
----                           -----
Amy                            555-1234
Eve                            555-6666
Ivy                            555-4223
Mia                            555-1327

PS C:\> "Amy's number is: " + $phonebook["amy"]
Amy's number is: 555-1234

在您的情况下,字典包含标识符单词(“String1”等)作为键,整个短语(“ABCD123X Execute String1”)作为与键关联的值。

使用此哈希表,您可以像这样进行替换File2.txt

if { $_ -match '^(\S+) procedure' } {
  # print the phrase from the $replacements hashtable if a matching line is found
  $replacements[$matches[1]]
} else {
  # otherwise print the original line
  $_
}

其余的你必须自己弄清楚,因为这是你的作业,不是我的。

于 2013-06-29T09:49:37.707 回答