Animesh D
Animesh D

Reputation: 5002

How can I remove repetitive text from a file?

I have a file which has a list of SQL Server databases. I want to remove the 4 system databases, [master,model,msdb,tempdb] from the file. How can I do that?

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

Upvotes: 1

Views: 184

Answers (4)

Shay Levy
Shay Levy

Reputation: 126762

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

Upvotes: 2

mjolinor
mjolinor

Reputation: 68273

One option is to use -notcontains

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

Upvotes: 3

Karoly Horvath
Karoly Horvath

Reputation: 96266

if you only want to remove lines:

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

if you want to remove the whole block:

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

Upvotes: 0

vonPryz
vonPryz

Reputation: 24071

Enumerate the file and check that the item doesn't matc a regexp. This is quite much like yi_H's grep -v example works.

# 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)\]")}

Upvotes: 1

Related Questions