如何用命令行替换文本文件中的每个前缀?

时间:2018-10-15 01:32:30

标签: regex windows powershell batch-file prefix

我有一个文本文件,看起来像这样:

0x1cb139c0 (110): file:///C:/Users/igues/Desktop/New folder/NOTEPAD.exe
0x1cb13f40 (110): file:///C:/Users/igues/Desktop/New folder/NOTEPAD.exe
0x1cb14bc0 (110): file:///C:/Users/igues/Desktop/New folder/NOTEPAD.exe
0x1cb38fc0 (104): file:///C:/Program Files/Everything/Everything.exe
0x1cb39fc0 (104): file:///C:/Program Files/Everything/Everything.exe
0x1cb3a040 (104): file:///C:/Program Files/Everything/Everything.exe
0x1cb43730 (100): file:///C:/Program Files/Notepad++/notepad++.exe
0x1cb44300 (100): file:///C:/Program Files/Notepad++/notepad++.exe
0x1cb44b50 (100): file:///C:/Program Files/Notepad++/notepad++.exe

我最终希望它看起来像这样:

C:/Users/igues/Desktop/New%20folder/NOTEPAD.exe
C:/Program Files/Everything/Everything.exe
C:/Program Files/Notepad++/notepad++.exe

如何使用命令行(或PowerShell)删除该烦人的前缀?我已经知道如何删除重复的行。我只需要在每行的开头删除此“ 0x ????????(???):file:/// C:/ ”前缀。


已修改以修复前缀。

3 个答案:

答案 0 :(得分:2)

PowerShell的基于正则表达式的-replace运算符非常适合于前缀剥离:

(Get-Content file.txt) -replace '^.*///'

正则表达式^.*///匹配从开始(.*^的所有字符(///),并且-由于没有替换字符串-默认情况下替换匹配的字符带有空字符串的字符串,即删除

答案 1 :(得分:1)

您可以使用 regex 类中的 Split 方法:

$file = Get-Content C:\file.txt
foreach ($line in $file) {
    [regex]::split($line, '///')[1]
}

结果,您可以将其保存到相同或另一个文件中。

答案 2 :(得分:0)

尝试一下:

Get-Content "C:\temp\test.txt" | %{($_ -split ': ')[1] -replace '/New folder/', '/New%20folder/'} | select -Unique