[英]Read & Update filestream
我有一个小工具,可以搜索许多文件。 我必须创建它,因为Google和Windows桌面搜索都没有在文件中找到适当的行。 搜索工作正常(我愿意对此进行改进),但我想添加到util中的一件事是批量查找/替换。
那么,从文件中读取行,将其与搜索词进行比较,如果通过则更新行,并继续浏览文件其余部分的最佳方法是什么?
我将对每个文件执行以下操作:
请注意,不要对二进制文件等执行此操作-对二进制文件进行文本搜索和替换通常会带来可怕的后果!
如果可以使用PowerShell,则可以使用以下定义的功能在文件之间执行查找和替换。 例如,要在当前目录的文本文件中查找'a string'
,您可以执行以下操作:
dir *.txt | FindReplace 'a string'
要将'a string'
替换为另一个值,只需在末尾添加新值即可:
dir *.txt | FindReplace 'a string' 'replacement string'
您还可以使用FindReplace -path MyFile.txt 'a string'
在单个文件上调用它。
function FindReplace( [string]$search, [string]$replace, [string[]]$path ) {
# Include paths from pipeline input.
$path += @($input)
# Find all matches in the specified files.
$matches = Select-String -path $path -pattern $search -simpleMatch
# If replacement value was given, perform replacements.
if( $replace ) {
# Group matches by file path.
$matches | group -property Path | % {
$content = Get-Content $_.Name
# Replace all matching lines in current file.
foreach( $match in $_.Group ) {
$index = $match.LineNumber - 1
$line = $content[$index]
$updatedLine = $line -replace $search,$replace
$content[$index] = $updatedLine
# Update match with new line value.
$match | Add-Member NoteProperty UpdatedLine $updatedLine
}
# Update file content.
Set-Content $_.Name $content
}
}
# Return matches.
$matches
}
请注意, Select-String
还支持正则表达式匹配,但为简单起见,已被限制为简单匹配;)您还可以像Jon建议的那样执行更可靠的替换,而不仅仅是用新内容覆盖文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.