【问题标题】:Bash newline in string grep [duplicate]字符串grep中的Bash换行符[重复]
【发布时间】:2018-07-08 21:47:03
【问题描述】:
$ cat ansible/file | grep "Other users"
Other users

如何在我的 grep 之后的新行上添加新字符串?

$ cat ansible/file | grep "Other users"
Other users
NewString  # New line with new string appended to file 

【问题讨论】:

  • 使用这个命令:cat ansible/file | grep "其他用户" | | awk '{print $0 "\nNewString"}'

标签: bash shell awk sed grep


【解决方案1】:

sed 用于在单独的行上执行 s/old/new/,仅此而已。对于其他任何事情,您应该使用 awk:

awk '{print} /Other users/{print "New Line"}' file

以上内容将在任何 UNIX 机器上的任何 shell 中的任何 awk 上稳健有效地工作,并且如果/当您的需求稍后发生变化时,增强/维护将是微不足道的。

【讨论】:

    【解决方案2】:

    您可以使用sed 找到您要查找的字符串,并将其替换为自身+新行:

    sed "s/Other users/Other users\nNew Line/g"
    

    我们将“Other users”替换为“Other users\nNew String”(即字符串本身,并在其后附加一个包含您要插入的内容的新行)。

    【讨论】:

    • 建议和观察:1) 使用单引号,除非需要双引号 2) 如果匹配行中有其他字符,则需要覆盖 3) \n 不可移植 4 ) sed 对此用例有 a 命令
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-27
    • 2017-01-21
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    • 2023-03-20
    • 2011-10-19
    相关资源
    最近更新 更多