如何从文件中删除重复文本?

时间:2011-06-16 10:44:27

标签: powershell powershell-v2.0

我有一个包含SQL Server数据库列表的文件。我想从文件中删除4个系统数据库,[master,model,msdb,tempdb]。我怎么能这样做?

Server1
[DB1]
[DB2]
[DB3]
[master]
[model]
[msdb]
[tempdb]
Server2
[DB1]
[DB2]
[DB3]
[master]
[model]
[msdb]
[tempdb]
Server3
[DB1]
[DB2]
[DB3]
[master]
[model]
[msdb]
[tempdb]

4 个答案:

答案 0 :(得分:3)

一种选择是使用-notcontains

 $system = "[master]","[model]","[msdb]","[tempdb]"
 $new_file = @(get-content db_list.txt |
   where {$system -notcontains $_})
 $new_file | out-file db_list.txt -force

答案 1 :(得分:2)

(Get-Content.\db.txt) | where {$_ -notmatch '^\[master|model|msdb|tempdb\]$'} | Out-File .\db.txt

答案 2 :(得分:1)

枚举文件并检查该项是否与正则表达式匹配。这非常像yi_H的grep -v示例。

# dbs is here an array, but anything enumerable works.
$dbs = @("[DB1]", "[DB2]", "[DB3]", "[master]", "[model]", "[msdb]", "[tempdb]", "Server2", "[DB1]", "[DB2]", "[DB3]", "[master]", "[model]", "[msdb]", "[tempdb]", "Server3", "[DB1]", "[DB2]", "[DB3]", "[master]", "[model]", "[msdb]", "[tempdb]")

$dbs | ? {!($_ -match "\[(master)|(model)|(msdb)|(tempdb)\]")}

答案 3 :(得分:0)

如果您只想删除行:

grep -v -E '^\[(master|model|msdb|tempdb)\]'

如果你想删除整个块:

perl -0133 -ne 'if ($_ !~ /^(master|model|msdb|tempdb)/) { print "["; print substr($_, 0, -1) }'