[英]Modify text of specific CSV column with regex
Note: The full script is at the bottom of the question.注意:完整的脚本在问题的底部。
Let's assume I have the following CSV file ( data.csv
).假设我有以下 CSV 文件( data.csv
)。 It's a simple file with 2 columns: a name and a path of the corresponding person's folder in drive D.这是一个包含 2 列的简单文件:驱动器 D 中相应人员文件夹的名称和路径。
name,path
A,D:\folder/A
B,D:\folder/B
C,D:\folder/C
D,D:\folder/D
E,D:\folder/E
I would like to change "/" to "" using the replace operator or method in PowerShell.我想使用 PowerShell 中的替换运算符或方法将“/”更改为“”。
I begin by importing the CSV file:我首先导入 CSV 文件:
$data = Import-Csv -Path "misc/data.csv"
Write-Output $data
name path
---- ----
A D:\folder/A
B D:\folder/B
C D:\folder/C
D D:\folder/D
E D:\folder/E
Then I use ForEach-Object
to perform the desired operation of the path
property like so:然后我使用ForEach-Object
来执行path
属性的所需操作,如下所示:
$data | ForEach-Object {
$_.path -replace "/", "\"
} | Write-Output
What I obtain is unfortunately an array of the modified values:不幸的是,我得到的是一组修改后的值:
D:\folder\A
D:\folder\B
D:\folder\C
D:\folder\D
D:\folder\E
After looking at a few examples on the internet, I also tried this:在网上看了几个例子后,我也试过这个:
$data | ForEach-Object {
$_.path -replace "/", "\"
$_
} | Write-Output
The result I got was definitely unexpected for me:我得到的结果绝对出乎我的意料:
name path
---- ----
A D:\folder/A
D:\folder\B
B D:\folder/B
D:\folder\C
C D:\folder/C
D:\folder\D
D D:\folder/D
D:\folder\E
E D:\folder/E
Would you please advice?请您给点建议好吗? Thank you in advance.先感谢您。
Full script:完整脚本:
# Import CSV file
$data = Import-Csv -Path "misc/data.csv"
Write-Output $data
# Method 1
$data | ForEach-Object {
$_.path -replace "/", "\"
} | Write-Output
# Method 2
$data | ForEach-Object {
$_.path -replace "/", "\"
$_
} | Write-Output
My appreciation goes to @Doug Maurer who pointed out that the modified values need to be assigned back to the path
property.我感谢@Doug Maurer,他指出修改后的值需要分配回path
属性。 The solution is therefore:因此解决方案是:
$data = Import-Csv -Path "misc/data.csv"
$data | ForEach-Object {
$_.path = $_.path -replace "/", "\"
$_
}
name path
---- ----
A D:\folder\A
B D:\folder\B
C D:\folder\C
D D:\folder\D
E D:\folder\E
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.