【发布时间】:2015-03-29 05:54:22
【问题描述】:
请帮助我创建一个脚本来执行如下所述的任务。
我有 2 个文件,A.txt 和 B.txt。 A.txt 的内容如下所示
现在我需要在A.txt 中搜索单词"FRUIT" 并将"FRUIT" 顶部的第二行复制到一个名为list.txt 的新文件中。
但我只需要水果的名称,list.txt 应该如下所示。
这是我执行此操作的编码(powershell)...
$source = "C:\temp\A.txt"
$destination = "C:\temp\list.txt"
$hits = select-string -Path $source -SimpleMatch "type FRUIT" -CaseSensitive
$filecontents = get-content $source
foreach($hit in $hits)
{
$filecontents[$hit.linenumber-3]| out-file -append $destination
"" |out-file -append $destination
}
这将提取下面的第二行
名称苹果 名字猩猩 名称奇瑞下面的编码(.bat)将删除单词"name"
@echo off
setlocal enabledelayedexpansion
del list2.txt
for /f "tokens=*" %%a in (C:\temp\list.txt) do (
set line=%%a
set chars=!line:~-13,13!
echo !chars! >> list2.txt
)
作为第二阶段,现在我需要在B.txt 的list.txt 文件(APPLE,ORANG,CHERY)中搜索单词,如下所示。
我必须在B.txt 中搜索来自list.txt 的单词并提取顶部的3 行并将其相应地写入一个名为done.txt 的新文件中。下面是我的编码(powershell)。
$source = "C:\temp\B.txt"
$destination = "C:\temp\done.txt"
$patterns = Get-Content c:\temp\list2.txt | Where-Object{$_}
$results = Select-String c:\temp\done.txt -Pattern $patterns -SimpleMatch
$results.Line | ForEach-Object{"$_`r`n"} | Set-Content c:\temp\done.txt
foreach($hit in $hits)
{
$filecontents[$hit.linenumber-4]| out-file -append $destination
$filecontents[$hit.linenumber-3]| out-file -append $destination
$filecontents[$hit.linenumber-2]| out-file -append $destination
$filecontents[$hit.linenumber-1]| out-file -append $destination
"" |out-file -append $destination
}
我设法为此开发了编码。但我需要 3 个脚本文件(2 个 powershell 和 1 个批处理)来完成此操作。
请帮助我在一个脚本中完成此任务。最好是 .vbs 或 .bat 格式。
【问题讨论】:
-
我认为你需要退后几步,再看一遍并重新考虑。如果您要返回以匹配其他“name FRUIT”字符串,则从“name FRUIT”字符串中提取水果名称似乎毫无意义。你有一个完全匹配你正在寻找的开始。此外,您说您需要 2 个 Powershell 脚本,然后说“最好在 .vbs 或 .bat 中”。我认为没有人会愿意在周六的大部分时间里试图跳过那个圈子,
标签: powershell batch-file text