【问题标题】:bash script to edit all files in a dir用于编辑目录中所有文件的 bash 脚本
【发布时间】:2018-10-29 10:44:31
【问题描述】:

尝试编辑聊天目录中的所有日志文件,以替换在给定值之后的下一行中找到的字符串值。

以下代码有效:

sed '/Did cool stuff/{n;s/how cool/sweet as bru/g} logname.log

但是当尝试执行 bash 时,它永远不会完成,只是挂起:

#!home/bin/bash
for file in /home/logs/*.log ; do
    sed '/Did cool stuff/{n;s/how cool/sweet as bru/g}' ;
done

感觉好像我遗漏了一些明显的东西。

【问题讨论】:

    标签: linux bash loops sed


    【解决方案1】:

    对于for 循环,您需要命令行中的循环变量,如果您不设置文件名,sed 将从标准输入读取,脚本将挂起等待输入。

    #!/bin/bash
    for file in /home/logs/*.log ; do
        sed '/Did cool stuff/{n;s/how cool/sweet as bru/g}' "$file";
    done
    

    但是for 不需要,sed 已经可以做到了。

    sed '/Did cool stuff/{n;s/how cool/sweet as bru/g}' /home/logs/*.log
    

    如果您想更改文件内容而不是显示更改后的版本,请使用-i

    sed -i '/Did cool stuff/{n;s/how cool/sweet as bru/g}' /home/logs/*.log
    

    【讨论】:

    • 谢谢忘记文件名-明显错误
    • 工作正常,除非第一个和第二个字符串中有重复行; EX LINE 4 '做了很酷的事情' ; LINE5 '做了很酷的事情' ; LINE6 '多么酷';第 6 行不能替代
    猜你喜欢
    • 1970-01-01
    • 2010-12-05
    • 1970-01-01
    • 2010-12-29
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    相关资源
    最近更新 更多