我在制作一个批处理文件时遇到了一个问题。export.dat
而我没有办法将CSV字段项从5位改为6位.这是一个首选的老程序.至于新程序我可以添加必填项。
D,1,2126,4372,T,125P,,255473730,person,n,person,19800320,07833,300.00,07833,300.00,078330
必须是修改后的。
D,1,2126,4372,T,125P,,255473730,person,n,person,19800320,078330,300.00,078330 - A03.1 - Shigellosis d,,etc
所以我们有一个领先的资本 D
后面跟着13个逗号,批处理应该在逗号13前加一个零。
@echo off
setlocal
set "target=.\export.dat"
set "destination=.\updated.dat"
powershell -noprofile -command^
"$content = get-content -literalpath '%target%';"^
"$modifiedContent = @();"^
"$modifiedContent += $content[0];"^
"ForEach ($line in $content[1 .. ($content.count - 1)]) {"^
" if ($line.startswith('D,')) {"^
" $items = $line.split(',');"^
" if ($items.length -gt 14) {$items[14] += '0'; $line = $items -join ','};"^
" };"^
" $modifiedContent += $line"^
"};"^
"$modifiedContent | set-content -literalpath '%destination%'"
Powershell有 Import-CSV
和 Export-CSV
它可以处理CSV文件,尽管 Export-CSV
输出带有双引号字段项的数据。Powershell 7 引入了引号参数,用于 Export-CSV
,虽然目前还是新的。在Powershell不到7的情况下,建议用 Get-Content
去掉双引号,使用 Set-Content
. 由于示例内容缺乏双引号,我决定使用 Get-Content
,用逗号分割并写上 Set-Content
.
下面的代码是一个混合代码 批处理文件 与 权力壳 它有一些注释,解释了这些代码不适合插入到一个单独的 powershell 命令中。
<# :: Begin bat code
@echo off
setlocal
set "target=.\export.dat"
set "destination=.\updated.dat"
powershell -noprofile "invoke-expression(get-content '%~f0' | out-string)"
exit /b 0
#> ## Begin ps1 code
# Filepaths from environment variables.
$target = $env:target
$destination = $env:destination
# Read file content into a variable.
$content = get-content -literalpath $target
# Create an empty array for modified content.
$modifiedContent = @()
# Add 1st line as unmodified header.
$modifiedContent += $content[0]
# Add the rest of the lines.
foreach ($line in $content[1 .. ($content.length - 1)]) {
# Require a leading capital D to modify a line.
if ($line.startswith('D,')) {
# Split by commas.
$items = $line.split(',')
# Modify item 14.
if ($items.length -gt 14) {
$items[14] += '0'
$line = $items -join ','
}
}
# Add line to array.
$modifiedContent += $line
}
# Write modified content to destination file.
$modifiedContent | set-content -literalpath $destination
如果合适的话,可以将 powershell 代码部分复制到一个 .ps1
文件,只需将 $target = $env:target
和 $destination = $env:destination
与 $target = '.\export.dat'
和 $destination = '.\updated.dat'
.
输入 export.dat:
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 D,1,2126,4372,T,125P,,255473730,person,n,person,19800320,07833,300.00,07833,300.00,078330 D,1,2126,4372,T,125P,,255473730,person,n,person,19800320,07833,300.00 d,1,2126,4372,T,125P,,255473730,person,n,person,19800320,07833,300.00,07833,300.00,078330
输出 updated.dat:
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 D,1,2126,4372,T,125P,,255473730,person,n,person,19800320,07833,300.00,078330,300.00,078330 D,1,2126,4372,T,125P,,255473730,person,n,person,19800320,07833,300.00 d,1,2126,4372,T,125P,,255473730,person,n,person,19800320,07833,300.00,07833,300.00,078330
D,
作为 d,
不符合相同的情况,所以不做修改。