简体   繁体   English

使用powershell在csv中删除空格和列

[英]Delete spaces and column in csv with powershell

I'm trying to convert a downloaded ".txt" file into a goodlooking and useful ".csv" file using powershell. 我正在尝试使用powershell将下载的“ .txt”文件转换为美观且有用的“ .csv”文件。 I'm kindly advanced with this task but shortly before the goal I have some problems which I can not manage. 我已经完成了这项任务,但是在实现目标之前不久,我遇到了一些我无法解决的问题。

It is a list with the OUI-Part of mac-addresses and its names. 它是一个列表,其中包含mac地址的OUI部分及其名称。 This is how it looks like (without quotation): 这是它的样子(不带引号):

" 00-00-00   "  EMPTY COLUMN    "XEROX CORPORATION"
" 00-00-01   "  EMPTY COLUMN    "XEROX CORPORATION"

My first question now is, how can I get the spaces in the column of the OUI-address away. 现在,我的第一个问题是,如何删除OUI地址列中的空格。 The secound one, how can I delete the empty column. 第二,如何删除空列。

In the end it should look like this (without quotation): 最后,它应该看起来像这样(不带引号):

"00-00-00" "XEROX CORPORATION"
"00-00-01" "XEROX CORPORATION"

So that we have in the first column the OUI without any spaces and in the second column the name of the company. 这样我们在第一列中的OUI中没有任何空格,在第二列中的公司名称。 But here it is important to have spaces in the name. 但是,在此名称中必须有空格。

Original file content: 原始文件内容:

  00-00-09          XEROX CORPORATION
  00-00-0A          OMRON TATEISI ELECTRONICS CO.
  00-00-0B          MATRIX CORPORATION
  00-00-0C          CISCO SYSTEMS, INC.

I hope you can help me. 我希望你能帮助我。

Here is one way, using Get-Content and Select-String with a regular expression to extract the substrings: 这是使用带有正则表达式的Get-ContentSelect-String提取子字符串的一种方法:

get-content "test.txt" | foreach-object {
  $_ | select-string '\s*((?:[0-9a-f]{2}-){2}[0-9a-f]{2})\s+(.+)$' | foreach-object {
    $oui = $_.Matches[0].Groups[1].Value
    $description = $_.Matches[0].Groups[2].Value
  }
  new-object PSObject -property @{
    "OUI" = $oui
    "Description" = $description
  } | select-object OUI,Description
}

For output that contains pairs of quoted strings, replace New-Object with a formatted string; 对于包含一对带引号的字符串的输出,请将New-Object替换为格式化的字符串; for example: 例如:

get-content "test.txt" | foreach-object {
  $_ | select-string '\s*((?:[0-9a-f]{2}-){2}[0-9a-f]{2})\s+(.+)$' | foreach-object {
    $oui = $_.Matches[0].Groups[1].Value
    $description = $_.Matches[0].Groups[2].Value
  }
  '"{0}" "{1}"' -f $oui,$description
}

You can use a regular expression tester such as https://www.regex101.com/ to see how the regular expression (ie, the parameter to Select-String ) extracts the substrings. 您可以使用正则表达式测试器(例如https://www.regex101.com/)来查看正则表达式(即Select-String的参数)如何提取子字符串。

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

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