【问题标题】:Inserting a new line in html format file using powershell使用powershell在html格式文件中插入新行
【发布时间】:2013-09-19 13:58:11
【问题描述】:

我正在尝试在格式类似于 HTML 的文件中插入一行

这就是我正在运行的内容

$ID = read-host "ENTER NEW ID"
$infile = C:\testfile
$outfile = C:\testfileout
Get-Content $infile |`
  foreach-object {$_ -replace "<string>ABCD</string>", "<string>ABCD</string> <string>$ID</string>"} |`
  set-content $outfile

我遇到的问题是该文件可以工作,但只是我第一次这样做。我宁愿有一个更有说服力的解决方案,它会寻找&lt;string&gt;(即&lt;array&gt;)的父标头,但我找不到一个好的解决方案。 &lt;master&gt;节点下还有多个&lt;array&gt;节点。

编辑:这是一个示例

<plist version="1.0">
 <dict>
  <key>XYZ</key>
  <string>ID</string>
  <key>APID</key>
  <array>
    <string>!@#$$!!</string>
  </array>
  <key>CreationDate</key>
  <date>9/20/2013</date>
  <key>Cert</key>
  <array>
    <data>
    abcs
    </data>
  </array>
  <key>ZZZ</key>
 <dict>
    <key>APID</key>
    <string>Filename</string>
    <key>get</key>
    <false/>
    <key>chain</key>
    <array>
        <string>oohhui</string>
    </array>
 </dict>
 <key>EXP</key>
 <date>9/21/2013</date>
 <key>Name</key>
 <string>Con</string>
 <key>IDstring</key>
 <array>
    <string>ABCD</string>
    <string>hdhd</string>
    </array>

【问题讨论】:

  • 感觉你的问题太笼统了,不好回答。为什么一定要看父母?拥有多个 标签有什么意义?如果你已经达到了你的目的,为什么还要运行多次?
  • 如果和html类似的话,也许它实际上是XML,你可以使用XML API策略吗?更高版本的 powershell 内置了 xml 作为第一类数据类型。
  • 请提供示例(示例输入文件的内容和所需的输出)。
  • 我添加了一个内容结构的例子

标签: powershell insertion


【解决方案1】:

假设您的文件与 xml 格式兼容,您可以使用类似的东西

[xml]$x=gc c:\temp\test.xml
$x.plist.dict.key | %{$_ -replace 'XYZ','ABC'} #will replace any XYZ key value by ABC value;

【讨论】:

  • 我不想替换值,我想插入一个新行。我能想到的唯一方法是替换命令。它基本上不会是一个节点吗?
【解决方案2】:

试试这样的:

$ID = ...

[xml]$plist = gc 'C:\path\to\your.plist'
$node = $plist.SelectSingleNode("//array/string[text()='ABCD']")

$newNode = $plist.CreateElement('string')
$newNode.AppendChild($plist.CreateTextNode($ID)) >$null

$node.ParentNode.InsertAfter($newNode, $node)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 2020-06-18
    • 2013-06-30
    相关资源
    最近更新 更多