使用powershell从CSV中提取数据并重新格式化

gg0vcinb  于 2023-07-31  发布在  Shell
关注(0)|答案(2)|浏览(132)

我在CSV文件的单元格A2中有数据(没有标题),看起来像这样:报告日期:23年7月20日
我如何使用PowerShell从文件中读取此单元格,去掉除日期值以外的所有内容,并将其重新格式化为:年月日
我不需要从文件中读取任何其他数据,并且没有标题,但在文件的第一行中有其他数据。我无法修改源CSV。
我已经尝试了这里的例子的变体,但没有运气:get specific cell value in csv file using powershell
这将返回“WARNING:未指定一个或多个标头。以“H”开头的默认名称已用于替换任何丢失的标头。”但没有实际值。

ltskdhd1

ltskdhd11#

可以将Import-Csv cmdlet与-Header参数沿着使用,以指定标头名称。由于CSV文件没有标题,因此可以提供虚拟标题名称。然后,您可以通过引用相应的标题和行来访问单元格值。
你可以这样做:

# Define the path to the CSV file and dummy header name
$csvFilePath = "path\to\your\file.csv"
$headerName = "Header"

# Import the CSV file with the dummy header

$data = Import-Csv -Path $csvFilePath -Header $headerName

# Get the value from cell A2

$value = $data | Where-Object { $_.PSObject.Properties.Name -eq 
$headerName } | Select-Object -ExpandProperty $headerName

# Extract the date from the value (assuming it's always at the end of the string)

$date = $value.Substring($value.LastIndexOf(":") + 2).Trim()

# Reformat the date to YY-MM-DD

$formattedDate = Get-Date $date -Format "yy-MM-dd"

# Output the result

Write-Output $formattedDate

字符串

neekobn8

neekobn82#

我无法让@RarikmilkraiSouza脚本工作,但它确实帮助我弄清楚我需要去哪里。这是我最终得到的,它做了我需要的:

# Define the path to the CSV file and dummy header name
$csvFilePath = "C:\testfile.csv"
$headerName = "ColumnA"

# Import the CSV file with the dummy header

$data = Import-Csv -Path $csvFilePath -Header $headerName

# Get the value from cell A2

$value = $data[1].'ColumnA'

# Extract the date from the value and reformat to YY-MM-DD

$rptdate = $value -replace 'RPT Date :(\d{2})/(\d{2})/(\d{2})','$3-$1-$2'
$formattedDate = "20" + $rptdate

# Output the result

Write-Output $formattedDate

字符串

相关问题