PowerShell根据内容替换文本文件中的多个元素

时间:2013-04-03 10:27:50

标签: powershell powershell-v3.0

提前感谢您的时间。

我是PowerShell的新手,尝试编写一个脚本,可以搜索一堆文本文件并挑选出某些元素,然后使用它们来替换其他元素。以下是内容示例:

OrderLine="0002" <Image>11770060002_outside.jpg</Image><Image>11770060002_inside.jpg</Image>
OrderLine="0003" <Image>11770060003_outside.jpg</Image><Image>11770060003_inside.jpg</Image>

所以我要做的就是逐步完成,选择'OrderLine'值并将其放入变量中,然后替换'Image'值 - 显示预期输出可能比尝试解释它更容易!

OrderLine="0002" <Image>11770060002.pdf</Image>
OrderLine="0003" <Image>11770060003.pdf</Image>

如您所见,文件名已被替换,名称的结尾与OrderLine相同。

表示文件中只能有一个订单行,或者可能只有150个订单行。

我知道它看起来像XML,但它无效(不要问)因此它不会解析,需要是基于文本的解决方案。

感谢任何帮助!

编辑:这是我到目前为止所做的,这是有用的,但是它取自文件名的值(与文件中的第一个条目相同,即0001),因此它仅适用于具有单个订单的文件。我需要更新例程以处理上面的多个OrderLine条目。

$File_Folder = "C:\PSTEST\TEST\"
$Output_Folder = "C:\PSTEST\TEST\OUTPUT\"

$array = Get-ChildItem $File_Folder\*.xml

foreach($item in $array){

$xml_filename = $item.FullName.substring($File_Folder.Length)

$just_filename = $xml_filename -replace ".xml", ""
$just_filename = $just_filename -replace "Order_PO", ""

$replace_outside_original = '<image>' + $just_filename + '_outside.jpg</Image>'
$replace_outside_with = '<image>' + $just_filename + '.pdf</image>'

$replace_inside_original = '<image>' + $just_filename + '_inside.jpg</Image>'
$replace_inside_with = ''

$destination_file = $Output_Folder + 'Order_PO' + $just_filename + '.xml'

(Get-Content $File_Folder\$xml_filename) | Foreach-Object {
    $_ -replace $replace_outside_original, $replace_outside_with `
       -replace $replace_inside_original, $replace_inside_with `
    } | Set-Content $destination_file
}

2 个答案:

答案 0 :(得分:0)

使用正则表达式:

从您需要匹配的其中一行开始:

OrderLine =“0002”11770060002_outside.jpg11770060002_inside.jpg

用正则表达式元字符替换变量部分。在这种情况下,可变数据是数字:

$regex  = 'OrderLine="\d+" <Image>\d+_outside.jpg</Image><Image>\d+_inside.jpg</Image>'

然后为要保留的部分添加分组parens:

$regex  = '(OrderLine="\d+" <Image>\d+_outside.jpg</Image>)<Image>\d+_inside.jpg</Image>'

然后使用-match过滤掉与正则表达式匹配的行,a -replace与捕获组的反向引用进行修剪,另一个替换为替换文本的文字部分,然后将结果输出到另一个文件。

(get-content file.txt) -match $regex -replace $regex,'$1' -replace '_outside\.jpg','.pdf' |
 set-content newfile.txt

答案 1 :(得分:0)

成功!如果没有mjolinor的帮助,我无法做到这一点,感谢花时间帮助我,我真的很感激。

最后我通过替换一个然后运行并执行另一个来提交它,我认为这是输出真/假的匹配语句而我没有掌握它的技能。这种方式并不是最干净的,但它完成了工作:

$File_Folder = "C:\PSTEST\TEST\"
$regex  = '<Image>\d+_inside.jpg</Image>'
$array = Get-ChildItem $File_Folder\*.xml | ForEach-Object { (Get-Content $_) -replace '_outside\.jpg','.pdf' | Set-Content -path $_ }
$array = Get-ChildItem $File_Folder\*.xml | ForEach-Object { (Get-Content $_) -replace $regex,'' | Set-Content -path $_ }