简体   繁体   English

使用Powershell从CSV的列中的字符中删除字符串

[英]Remove String from Character from column in CSV using Powershell

I have a CSV file containing two columns:server name with domain and date 我有一个包含两列的CSV文件:服务器名称以及域和日期

servername.domain.domain.com,10/15/2018 6:28
servername1.domain.domain.com,10/13/2018 7:28

I need to remove the fully qualified name so it only has the shortname and I need to keep the second column so it looks as is like below either by sending to a new CSV or somehow removing the domain inplace somehow. 我需要删除完全限定的名称,以便它仅包含短名称,并且需要保留第二列,以便通过发送到新的CSV或以某种方式就地删除域来使其看起来像下面。 Basically I want the second column untouched but I need it to be included when creating a new CSV with the altered column 1. 基本上,我希望第二列保持不变,但是在创建具有更改的列1的新CSV时,我需要将其包括在内。

servername,10/15/2018 6:28
servername1,10/13/2018 7:28

I have this: 我有这个:

Import-Csv "filename.csv" -Header b1,b2 |
    % {$_.b1.Split('.')[0]} |
    Set-Content "filename1.csv"

This works great, but the problem is the new CSV is missing the 2nd column. 这很好用,但是问题是新的CSV缺少第二列。 I need to send the second column to the new CSV file as well. 我还需要将第二列发送到新的CSV文件。

Use a calculated property to replace the property you want changed, but leave everything else untouched: 使用计算所得的属性来替换您要更改的属性,但不要更改其他所有内容:

Import-Csv 'input.csv' -Header 'b1', 'b2' |
    Select-Object -Property @{n='b1';e={$_.b1.Split('.')[0]}}, * -Exclude b1 |
    Export-Csv 'output.csv' -NoType

Note that you only need to use the parameter -Header if your CSV data doesn't already have a header line. 请注意,如果您的CSV数据尚无标题行,则仅需要使用参数-Header Otherwise you should remove the parameter. 否则,您应该删除该参数。

If your input file doesn't have headers and you want to create the output file also without headers you can't use Export-Csv , though. 如果您的输入文件没有标题,并且您也想创建没有标题的输出文件,则不能使用Export-Csv Use ConvertTo-Csv to create the CSV text output, then skip over the first line (to remove the headers) and write the rest to the output file with Set-Content . 使用ConvertTo-Csv创建CSV文本输出,然后跳过第一行(以除去标题),然后将其余Set-Content通过Set-Content写入输出文件。

Import-Csv 'input.csv' -Header 'b1', 'b2' |
    Select-Object -Property @{n='b1';e={$_.b1.Split('.')[0]}}, * -Exclude b1 |
    ConvertTo-Csv -NoType |
    Select-Object -Skip 1 |
    Set-Content 'output.csv'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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