【问题标题】:How do I prepend a string to each file in directory that matches my pattern?如何在与我的模式匹配的目录中的每个文件前添加一个字符串?
【发布时间】:2010-11-10 13:00:51
【问题描述】:

我正在尝试将 require_once 'bootstrap.php'; 字符串添加到特定目录中的每个 schema.yml 文件中。我是linux新手。有人可以告诉我one-line-magic-command 吗?

非常感谢任何帮助!

编辑 我需要递归搜索 schema.yml。

【问题讨论】:

标签: linux bash scripting


【解决方案1】:

使用 sed:

find somedir -name schema.yml | xargs sed -i "1i require_once 'bootstrap.php';"

【讨论】:

  • 我不得不稍微修改它以使其在我的 Mac 上工作。我将最终结果发布为separate answer,因此我可以为其添加必要的格式。
【解决方案2】:
find somedir -name schema.yml | \
   xargs perl -i.orig -pe 'print "require_once \x27bootstrap.yml\x27\n" if $. == 1; close ARGV if eof' 

【讨论】:

  • 找到 . -name schema.yml | xargs perl -i.orig -pe 'print "require_once \x27bootstrap.php\x27\n";如果 $。 == 1; close ARGV if eof' ---- 此命令抛出错误:-e 第 1 行的语法错误,在“if $”附近。由于编译错误,-e 的执行中止。 xargs: perl: 以状态 255 退出;中止
【解决方案3】:

您可能需要检查“bootrstap.yml”的拼写...

#!/bin/bash
TMPFILE=/tmp/reallyuniquetempnamewhateveryouchoose
for f in `find . -name schema.yml`
do
    echo "require_once 'bootrstap.yml';" > $TMPFILE
    cat $f >> $TMPFILE
    mv -v $TMPFILE $f
done

编辑:好吧,上面的单线更好,即使一开始有点难以理解:)

【讨论】:

  • 两个输出合二为一:echo "foo" | cat - file > "$TMPFILE"。注意引号的使用:mv "$TMPFILE" "$f"。如果目录名称包含空格,for ... $(find) 将失败。使用find ... | while read -r f
【解决方案4】:

这是@dogbane 的回答的后续,我很喜欢,但需要一些调整才能在我的 Mac 上正常工作。 (我试图将其发布为对他的回答的评论,但我认为您不能将所有这些格式都放在评论中。)

我最终得到:

find somedir -name schema.yml | xargs sed -i '' "1i\\
require_once 'bootstrap.php';
"

具体来说,变化是:

  1. sed-i 选项(用于就地编辑的备份文件的扩展名)需要一个参数,但空引号就足够了(告诉它不要创建备份文件)。李>
  2. sed 命令需要在地址后有一个\(但转义,因为它在双引号中,所以它以\\ 结尾),然后是换行符,然后是要添加的文本,然后是另一个换行符,然后是右引号。

【讨论】:

  • 感谢您回答这个老问题。我想有人会觉得这很有用。
【解决方案5】:

创建一个快速的python脚本:

prepend_my_text.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os
from os.path import join

TEXT = """require_once 'bootstrap.php';\n"""

def main():
    for dirpath, _, files in os.walk("."):
        for f in files:
            if f == "schema.yml":
                with file(join(dirpath, f), 'r') as original: data = original.read()
                with file(join(dirpath, f), 'w') as modified: modified.write(TEXT + data)

if __name__ == '__main__':
    main()

并在您正在搜索的目录中运行它: $ chmod +x prepend.py $ ./prepend.py

好处是您可以使用字符串文字(python 中的三引号)来避免担心转义字符

【讨论】:

    猜你喜欢
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    相关资源
    最近更新 更多