【问题标题】:Change some fields in a file更改文件中的某些字段
【发布时间】:2014-06-03 12:28:30
【问题描述】:

我需要分析一个文件并更改一些字段。 示例:

<taskdef uri="xxxxxx" resource="/mnt/data/yyy.xml">
    <classpath path="/mnt/data/test.jar"/>
</taskdef>

<target name="test"
    description="this is a xml file">
       <fileset dir="/tmp/data/output/test_1/" includes=all/>

就我而言,我需要找到这部分:

    <fileset dir="/tmp/data/output/test_1/" includes=all/>

只更改名称(例如)test_1 最后保存文件

【问题讨论】:

  • 使用 Nokogiri,解析 xml 并做所有你需要的改变。然后将 XML 保存到一个新文件中。
  • 不幸的是我不能使用像 Nokogiri 这样的库来解析文件
  • 你可以使用正则表达式来找到它,但是重新发明轮子是个坏主意,你为什么不能使用 gems ?

标签: ruby string file


【解决方案1】:

在你的评论中你说你“不能使用像 Nogokiri 这样的库来解析文件”。所以我只能猜测你没有进行完整的 XML 解析。

假设您不必解析 XML,您可以在有问题的行上使用 Ruby 的 String.replace 方法。只需遍历文件中的行,直到找到有问题的行并调用替换。这是一些伪代码。

open file
for each line
  is this what I want to change
  change line
save (new) file

【讨论】:

  • 你是对的(对不起,我认为我的帖子不清楚),我正在做一个通用解析。现在我用 File.readlines(FILE) 读取每一行。每个都做 |line|然后用 line_parsed = line.split(/ /) 拆分它们。但是在 line_parse[1] 中我没有...任何想法?
  • 将您的代码 sn-p 添加到问题中。这连同示例数据将帮助我们确定您的问题。
猜你喜欢
  • 2023-01-18
  • 1970-01-01
  • 2021-07-21
  • 1970-01-01
  • 1970-01-01
  • 2021-07-22
  • 2018-10-13
  • 2015-12-26
  • 2011-02-22
相关资源
最近更新 更多