繁体   English   中英

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

[英]Replaces the text in the given file - FAKE F#MAKE

我是FAKE的新手,并试图在FAKE中实现一些东西,如下所述:我有一个超过100行的文件,我想在代码中改变几行,假设我想改变第二行,即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
    )
)

例如,如果您只在一个文件中有一组要匹配的特定字符串,那将非常有用。 但是,有一个更简单的函数,名为ReplaceInFiles (注意复数),它允许您一次替换多个文件中的文本。 此外, ReplaceInFiles不是将函数作为参数,而是采用一系列 (old,new)对。 这通常更容易编写:

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.12IFR.SIIC._0.45ABC.WXYZ._0.12ABC.WXYZ._0.45

您要使用哪一个都取决于您拥有多少文件,以及您需要多少个不同的替换字符串(以及将它们编写为正则表达式有多难)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM