简体   繁体   中英

Populate a specific column in a csv file using Powershell

As the title says, I want to populate a specific column in a CSV file by appending to the bottom of it.

Let's say we have a CSV table ( file.csv ) that looks like this:

     A       B        C              D
1 "text"   "word"  "phrase"       "term"
2 "number" "digit" "amount"       "numeral"
3 "letter" "char"  "hieroglyphic" "symbol"

In my PowerShell script, I have:

$foo = "x"

Out-File -FilePath file.CSV -Append -InputObject $foo

The result is this:

     A       B        C              D
1 "text"   "word"  "phrase"       "term"
2 "number" "digit" "amount"       "numeral"
3 "letter" "char"  "hieroglyphic" "symbol"
4   "x"

How do I get the value of $foo into a specific column such as C (below)?

     A       B        C              D
1 "text"   "word"  "phrase"       "term"
2 "number" "digit" "amount"       "numeral"
3 "letter" "char"  "hieroglyphic" "symbol"
4                    "x"

Let the value of the column number(starting with index 0) where you want the value be stored be in the variable column_number

$column_number = 1

You can use the Add-Content command as follows

Add-Content .\file.CSV -Value "$(","*$column_number)$foo"

This will append the value stored in $foo at the specified column number. Here is the documentation for the Add-Content command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM