0

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.

2 Answers 2

2

Try like this:

Import-Csv "CSV FILE Path" |
  Select-Object @{n='YOUR NEW COLUMN HEADER NAME';e={"file1"}},* |
    Export-Csv "CSV FILE Path"
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Wasif, That seems to do it. I will experiment further.
See this link which show the input and output. screencast.com/t/isY7Eqj6 I would prefer the output without any quotation marks. Also, I do not want the top two rows of the output. I used this syntax; import-csv input17.txt|select-object @{e={File1}},*|export-csv Output4
Actually, I just want to remove the first row, beginning, "#Type Selected.."
Thanks Doug, I have got rid of the header row. Do you know how I can get rid of the double quotes? Example: "File1","Row3 field1 field2 field3"
I guess that I really dont want a csv file output. Just an ordinary text file (not entirely sure of the difference)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.