简体   繁体   中英

Edit CSV header field with powershell

hope someone can help with PowerShell questions. I have a file like this

test1.dat

H,customername,4110,001,69,001
d,item,desc,number
d,item,desc,number
d,item,desc,number

What I would like to do is to change replace the last column (001) with the left 3 digits from the 3rd column(4110)

so it will be like this:

H,customername,4110,001,69,411
d,item,desc,number
d,item,desc,number
d,item,desc,number

I only want to modify the headers and not the details. I tried the code below.

$file = "C:\files\test1.dat"

 (Get-Content  $file)[0 .. 0] | Foreach-Object {$_ -replace "411", "001"} | 
Set-Content  $file

the problem with this is I have not found a way to use replace with left string to get the first 3 char from a field. This code will delete the details and only writes the first line.

Any help will be helpful,

thanks

Import the file:

$file = "C:\files\test.dat"
$dat = get-content $file

select first line:

$headers = $dat | select -first 1

split the first line into an array:

$headers = $headers -split ","

replace the last header with the first 3 chars of the third header:

$headers[5] = $headers[2].Substring(0,3)

join the array together in a string again, values are comma seperated:

$headers = $headers -join ","

Set the first line of your file to the joined String:

$dat[0] = $headers

Output the file:

$dat | set-content $file

Something like this should work:

$file = "C:\files\test1.dat"

$data = Get-Content $file

($data | select -First 1) -replace '^((?:.*?,){2}(...).*)...$', '$1$2' |
    Out-File $file
$data | select -Skip 1 | Out-File $file -Append

Regular expression breakdown:

  • ^(?:.*?,){2} matches the first two fields of the header line
  • (...) matches the next 3 characters and captures them in a group
  • ...$ matches the last 3 characters

The .* between ^(?:.*?,){2}(...) and ...$ matches the rest of the header line between the first 3 characters of the 3 rd field and the last 3 characters of the string. The outer parentheses group everything except the last 3 characters, so that it can be used in the replacement.

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