【问题标题】:Batch modify text files批量修改文本文件
【发布时间】:2015-05-10 07:40:01
【问题描述】:

我有一百万个 Markdown 文件分布在多个子目录文件中,这些文件具有不同的标题,我想更改这些文件:

# A Markdown title

---
title: "A Markdown title"
---

...同时保持文件的其余部分完好无损。有任何想法吗?首选 OS X 解决方案。

【问题讨论】:

  • 它们的结构都一样吗?如:# Another title 应转换为 title: "Another title"?
  • 它们都有不同的标题,但总是在一行上。
  • 如果你在 Linux 上,这是小菜一碟。

标签: regex markdown batch-processing


【解决方案1】:

您可以使用sed -i 's/^# \(.*\)$/---\ntitle: \"\1\"\n---/' ** 表示适用于当前目录下的所有文件。

或者使用 Unix find 搜索文件。示例用法:

find . -type f -name "*.java" -exec sed 's/^# \(.*\)$/---\ntitle: \"\1\"\n---/' "{}" > "{}.bak" \; -exec mv "{}.bak" "{}" \;

这会查找所有带有 java 扩展名的文件(在此目录和子目录中)并执行替换。它首先将内容存储在扩展名为 .bak 的文件中,然后将其移动到原始文件中。

您可以调整深度以使用find-maxdepth-mindepth 选项搜索文件。

【讨论】:

  • 谢谢,但我看到了 --> $ sed -i 's/^# (.*)$/---\ntitle: \"\1\"\n-- -/' * sed: 1: "test.md": undefined label 'est.md'
  • 您使用的是 Mac 吗? Mac 没有 -i 选项,您必须指定不同的输出文件。不过这是可以避免的。您要更改哪些文件?即它们是否具有相同的扩展名或其他任何共同点?
  • 是的,我在 OS X 上。所有文件都是 .md,有几个 markdown 标题和不同的文本。但每个只有一个“#title”(h1)。尝试了您的“查找”示例,但它将所有文件连接到一个 {}.bak 文件中,并且标题变为:'---ntitle:“JavaScript”n---'(不尊重新行)。非常感谢您的帮助!
  • 所以,我安装了brew install gnu-sed 并运行了gsed -i.backup -e 's/^# \(.*\)$/---\ntitle: \"\1\"\n---/g' *.md,这似乎可行。显然 OS X 上的默认 sed 版本不喜欢换行。
  • 很好,很高兴看到它现在工作!如果您的问题得到解决,请不要忘记接受答案!如果您想做更多这样的事情,那么绝对建议您也研究一下 GNU awk,这是另一个强大的命令行工具。
【解决方案2】:

在 Windows 中:使用记事本++“在文件中查找”选项。它搜索(一组)目录中的所有文件并替换文本。支持正则表达式。

在 Mac 上:使用内置的“查找”命令行工具。这里有更多信息:Batch replace text inside text file (Linux/OSX Commandline)

【讨论】:

    【解决方案3】:

    假设文件都在一个文件夹中,并且标题在第一行,那么执行此操作的 python 脚本将如下所示。

    for fn in os.listdir('.'):   # itterate through filenames in cwd
        f = open(fn,"rw+")       # make f a file object reading file name
        lines = f.readLines()    # Make an array of lines
        op = "---\n title:" +lines[0][2:]+"\n" #Assuming the title is the first line in the file.
        for k in lines[1:]:
            op += k + \n
        f.truncate()                            # Erase the old file
        f.write(op)                             # Write the file with the new title
        f.close()
    

    虽然这可以完成工作,但有明显更快的方法。

    【讨论】:

    • 谢谢,但由于我对 python 不太熟悉,所以我得到:line 6 op += k + \n ^ SyntaxError: unexpected character after line continuation character?
    猜你喜欢
    • 2015-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 2012-01-31
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多