Home > Blockchain >  Check if value in CSV in specific colum is empty
Check if value in CSV in specific colum is empty

Time:09-24

I have one CSV file with 3 columns (Header1, Header2, Header3) and I need to check if value for each row in column 2 (header2) is empty, if yes then value from Column 3 (Header 3) need to be copy to column 2 in same row. I hope it is clear.

Input Data

Header1,Header2,Header3,
ABC,123,123,
AXY,,456,
XYZ,,152,
ASD,528,,

Output

Header1,Header2,Header3,
ABC,123,123,
AXY,456,456,
XYZ,152,152,
ASD,528,,

I tired below code but it is not working

$csvFile1 = Import-Csv -Path "D:\AA_servers.txt" -Delimiter ","
$ht = @{}
foreach ($item in $csvFile1) {
    if ([string]::IsNullOrEmpty($item.Header2)) {
        $ht[$item.Header2] = $line.Header3
    }
} 
$csvFile1 | Export-Csv -Path "D:\AA_servers.txt" -Delimiter ";" -NoTypeInformation 

Thank you for support.

CodePudding user response:

I don't know what the purpose of the $ht variable is.
But dumping that makes the code work.

Proof of Concept:

$csv = ConvertFrom-Csv @'
Header1,Header2,Header3
ABC,123,124
AXY,,456
XYZ,,152
ASD,528,
'@

foreach ($row in $csv) {
    if ([string]::IsNullOrEmpty($row.Header2)) {
        $row.Header2 = $row.Header3
    }
} 
$csv

Output:

Header1 Header2 Header3
------- ------- -------
ABC     123     124
AXY     456     456
XYZ     15      15
ASD     528

For real usage:
(Just change the path.)

$csv = Import-Csv -Path 'D:\AA_servers.txt'

foreach ($row in $csv) {
    if ([string]::IsNullOrEmpty($row.Header2)) {
        $row.Header2 = $row.Header3
    }
}

$csv | Export-Csv -Path 'D:\AA_servers.txt' -NoTypeInformation
  • Related