Patrick
Patrick

Reputation: 9

Powershell - adding a string to each row

I have a csv with over 1,000 rows. In powershell how do I add a fixed string (e.g. "File1")to each row of the csv file. For example: Cat,dog,mouse should become file1,cat,dog,mouse.

Hopefully this is clear. Thanks for assistance.

Upvotes: 0

Views: 992

Answers (2)

Theo
Theo

Reputation: 61028

Looking at your latest comment, I think the fastest way here is to read the file line-by-line and output that same line with the wanted prefix attached.

Something like:

$prefix = 'File1'
$result = switch -File 'D:\Test\TheInputFile.csv' {
    default { "$prefix,$_" }
}

$result | Set-Content -Path 'D:\Test\TheOutputFile.csv'

If the input file is a csv with headers, you'll need to supply a new column header for the inserted field:

$prefix    = 'File1'
$header    = 'Path'  # or some other not already used column name
$firstLine = $true
$result = switch -File 'D:\Test\TheInputFile.csv' {
    default { 
        if ($firstLine) { "$header,$_"; $firstLine = $false } 
        else { "$prefix,$_" }
    }
}

$result | Set-Content -Path 'D:\Test\TheOutputFile.csv'

A CSV file is a text file. The difference is that in a csv, data is presented in a structured way. Ideally it starts with a header line, defining the field names for the rest of the lines which contain the actual data.
Each field is separated from the next by a specific character, usually a comma or semi-colon or tab.
To make sure a field can also include such a character, these fields must be enclosed in double-quotes.
See here

Upvotes: 0

wasif
wasif

Reputation: 15470

Try like this:

Import-Csv "CSV FILE Path" |
  Select-Object @{n='YOUR NEW COLUMN HEADER NAME';e={"file1"}},* |
    Export-Csv "CSV FILE Path"

Upvotes: 2

Related Questions