Automating process to multiply values in tab delimited file by -1 to negate them

为君一笑 提交于 2019-12-02 07:44:39

In PowerShell you can use Import-Csv for reading and Export-Csv for writing character-delimited files. Both cmdlets provide a parameter -Delimiter that allows you to specify the delimiter character:

$csv = Import-Csv 'C:\path\to\input.csv' -Delimiter "`t"
$csv | Export-Csv 'C:\path\to\output.csv' -Delimiter "`t" -NoType

Importing a CSV via Import-Csv gives you a list of custom objects where each field from the CSV is represented as a property of the object. You modify the fields by modifying the values of the properties before writing the data back to a file. To do this you can take either of the following two approaches:

  • Read the CSV completely into a variable, update the fields you want to modify in a loop, then export the data back to a file:

    $csv = Import-Csv ...
    foreach ($row in $csv) {
      [int]$row.B *= -1
      [int]$row.F *= -1
    }
    $csv | Export-Csv ...
    
  • Read the CSV into a pipeline and replace the fields you want to modify via calculated properties:

    Import-Csv ... |
      Select-Object -Include *,@{n='B';e={-$_.B}},@{n='F';e={-$_.F}} -Exclude B,F |
      Export-Csv ...
    

    Note that for this to work you must either use separate input and output files, or put the Import-Csv statement in parentheses. Otherwise Export-Csv would fail, because it can't write to the CSV while Import-Csv is still reading from it.

You can credit a button that's on your sheet anywhere you want that can run this macro. Assuming you know the basics of a macro/VBA (if you don't let me know) and A1 = -1 (can change in the below script).

Range("A1").Select
ActiveCell.FormulaR1C1 = "-1"
Range("B1:F1").Select
Range(Selection, Selection.End(xlDown)).Select
Range("A1").Select
Selection.Copy
Range("B1:F1").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlMultiply, _
    SkipBlanks:=False, Transpose:=False
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!