Reputation: 53
I have a Csv file which have huge data. I want a PowerShell script which will search for a line starting with number 19999
, if found then in that line replace whatever is between IISST:
and Progress
with word Result
.
Below is example of data.
1 ABC Test data Test data IISST: I am OK with this Progress some more data
1299 Someone needs this Test data IISST: I am OK with this Progress some more data
19999 ABC Test data Test data IISST: I want to replace this text with Result word Progress some more data
20000 ABC Test data Test data IISST: I am OK with this Progress some more data
79837 Someone needs this Test data IISST: I am OK with this Progress some more data
I have wrote below code after 3 days of struggle. and this code is removing all lines from file and adding only one line which I updated.
$search= [regex] "^19999"
$FullContentofLine= Get-Content "O:\Temp\test.csv" | select-string $search
$linenumber=$FullContentofLine.LineNumber
$linenumber
$fullContentofFile=Get-Content "O:\Temp\test.csv"
$contentUpdate = $fullContentofFile[$linenumber-1] -replace [regex] "IISST:(.*?)Progress","IISST: Result Progress"
#$contentUpdate
Set-Content "O:\Temp\test.csv" $contentUpdate
Upvotes: 2
Views: 451
Reputation: 59798
For this task I would recommend you the use of a switch
with the -File
parameter to read your file and the -Wildcard
parameter to match the lines starting with 19999
and containing IISST:
and Progress
.
For replacement of the line, there is no need to create a Regex
instance, the -replace
operator already understands regular expressions.
For the regex pattern being used, you can check https://regex101.com/r/adMCPg/1 for description.
$newContent = switch -Wildcard -File 'O:\Temp\test.csv' {
# look for lines starting with `19999` and containing `IISST:` and `Progress`
'19999*IISST:*Progress*' {
# if a line was matched,
# replace everything between `IISST:` and `Progress` with ` Result `
$_ -replace '(?<=IISST:).+(?=Progress)', ' Result '
# and go to next line
continue
}
# if the line was NOT matched, output it as-is
Default { $_ }
}
# replace the file with the new content
$newContent | Set-Content 'O:\Temp\test.csv'
Upvotes: 2