替换给定文件中的文本 - FAKE F#MAKE

Replaces the text in the given file - FAKE F#MAKE

我是 FAKE 的新手,正在尝试按照下面的描述在 FAKE 中实现一些东西: 我有一个超过 100 行的文件,我想更改代码中的几行,假设我想更改第 2 行,即 IFR.SIIC._0.12IFR.SIIC._0.45

我该怎么做。 我会使用 ReplaceInFile 或 RegexReplaceInFileWithEncoding 来执行此操作吗?

有许多函数可以为您提供帮助:您选择哪一个将取决于您喜欢如何编写代码。例如,ReplaceInFile 希望您为其提供 函数 ,而 RegexReplaceInFileWithEncoding 希望您为其提供 正则表达式 (以字符串形式,而不是 Regex 对象)。根据您要替换的文本,一个可能比另一个更容易。例如,您可以像这样使用 ReplaceInFile

Target "ChangeText" (fun _ ->
    "D:\Files\new\oneFile.txt"  // Note *no* !! operator to change a single file
    |> ReplaceInFile (fun input ->
        match input with
        | "IFR.SIIC._0.12" -> "IFR.SIIC._0.45"
        | "another string" -> "its replacement"
        | s -> s // Anything else gets returned unchanged
    )
)

如果您有一组要匹配的 specific 字符串,这将很有用,只是 single 文件。但是,有一个名为 ReplaceInFiles(注意复数形式)的更简单的函数,它允许您一次替换 多个 文件中的文本。此外,ReplaceInFiles 不是采用 function 作为参数,而是采用 sequence of (old,new) pairs。这通常更容易写:

let stringsToReplace = [
    ("IFR.SIIC._0.12", "IFR.SIIC._0.45") ;
    ("another string", "its replacement")
]
Target "ChangeText" (fun _ ->
    !! "D:\Files\new\*.txt"
    |> ReplaceInFiles stringsToReplace
)

如果您想以正则表达式的形式指定搜索和替换字符串,那么您需要 RegexReplaceInFileWithEncodingRegexReplaceInFilesWithEncoding(注意复数形式:前者采用单个文件,而后者需要多个文件)。我将仅向您展示一个多文件版本的示例:

Target "ChangeText" (fun _ ->
    !! "D:\Files\new\*.txt"
    |> RegexReplaceInFilesWithEncoding @"(?<part1>\w+)\.(?<part2>\w+)\._0\.12"
                                       @"${part1}.${part2}._0.45"
                                       System.Text.Encoding.UTF8
)

这样您就可以将 IFR.SIIC._0.12 更改为 IFR.SIIC._0.45,将 ABC.WXYZ._0.12 更改为 ABC.WXYZ._0.45

你想使用其中的哪一个取决于你有多少文件,你需要多少不同的替换字符串(以及将它们写成正则表达式的难度)。