【问题标题】:Find shell script and rename row查找 shell 脚本并重命名行
【发布时间】:2017-02-27 21:39:08
【问题描述】:

我有一个名为 script.sh 的 shell 脚本。我需要找到这个脚本并在脚本中更改值

发件人:

bash $current_dir/run.sh

./run.sh.x

我的解决方案是这样的:

find -maxdepth 10 -name "script.sh" -exec sed -i 's#bash '$current_dir'#run.sh#.#runs.sh.x#' {} \ ;

但我的命令仍然不起作用。知道如何在我的 shell 脚本中用新字符串替换这个字符串吗?

【问题讨论】:

    标签: bash shell sed find


    【解决方案1】:

    您的sed 表达似乎是问题所在。

    你可以使用:

    find . -maxdepth 10 -name "script.sh" -exec sed -i 's#bash \$current_dir/run\.sh#./run.sh.x#' {} +
    

    【讨论】:

    • 感谢您的快速回复。我有一个错误 - sed: can't read s#bash \$current_dir/run\.sh#./run.sh.x#: No such file or directory :-(
    • @Paul,如果您有 GNU sed,请删除 '' -- 这似乎是为 MacOS/BSD sed 编写的。
    • @Paul, ...sed-i 参数不是 POSIX 标准化的,因此不同的实现以不同的方式处理它;这些差异之一就是我们在这里。
    • @CharlesDuffy,是的,谢谢你的积极评价。我刚刚删除了引号'',现在对我来说似乎没问题。再次感谢你们。
    • @Paul:Charles 确实是对的,它在 OSX 上进行了测试。我从sed 命令中删除了额外的''
    【解决方案2】:

    回避sed 兼容性问题的一种方法是依赖perl。采纳BashFAQ #21的回答:

    search='bash $current_dir/run.sh'
    replace='./run.sh.x'
    in="$search" out="$replace" find . -name script.sh -exec \
      perl -pi -e 's/\Q$ENV{"in"}/$ENV{"out"}/g' '{}' +
    

    【讨论】:

      【解决方案3】:

      @anubhava 是正确的。另一个您可以使用的 sed 命令。

      find . -maxdepth 10 -name "script.sh" -type f | xargs -I {} sed -i 's/.*\/run.sh/\.\/run.sh.x/g' {}
      

      【讨论】:

      • @CharlesDuffy 感谢您的意见。我将文件放在包含空格的目录中,它仍然可以工作并且保持良好。 AFAIK,-I 也可以处理空格。
      • 其实你是对的。带有文字换行符的目录仍然是一个问题,但 -I {} 的行为与空格并没有错误。
      • 也就是说,为了演示在文件名中使用 xargs 而不使用 -0 和换行符时的错误:mkdir -p $'dir\nwith\nnewlines' && touch $'dir\nwith\nnewlines/script.sh'; find . -name script.sh | xargs -I {} printf '<%s>\n' {};输出为<dir><with><newlines/script.sh>
      • ...与正确行为相比:mkdir -p $'dir\nwith\nnewlines' && touch $'dir\nwith\nnewlines/script.sh'; find . -name script.sh -exec printf '<%s>\n' {} +;在这种情况下,输出是(正确)<dirwithnewlines/script.sh>
      • 我不否认它在常见情况下有效,我只是指出它引入了一些额外的错误(即使它们只在非常不寻常的情况下遇到),当它会可以编写没有它们的代码。奇怪的极端情况是安全漏洞的东西——想想有人用mkdir -p $'./tmp/\n/etc/passwd\n' && touch $'./tmp\n/etc/passwd\n/script.sh制作了一个恶意文件,欺骗你的代码修改/etc/passwd
      猜你喜欢
      • 2016-01-19
      • 2011-04-02
      • 2016-04-24
      • 2016-03-14
      • 1970-01-01
      • 2014-02-18
      • 2021-03-13
      • 1970-01-01
      • 2017-11-10
      相关资源
      最近更新 更多