【问题标题】:How to replace one line in multiple file on linux terminal? [duplicate]如何在linux终端上替换多个文件中的一行? [复制]
【发布时间】:2021-02-12 15:34:03
【问题描述】:

我有一个包含多个文件的文件夹,每个文件都包含一个类似的字符串

  "tree": "/a/anything-here/b/"

对于每个文件,我需要用字符串替换内部 "//" 之间的内容,在这种情况下 "anything-here"

我使用sed 命令没有成功,你能帮帮我吗?

sed -i 's/"root": a/b" .

【问题讨论】:

  • 看起来像 JSON 字段?不要使用像 sed 这样的非语法感知解析器以防万一

标签: regex awk sed


【解决方案1】:

你可以使用这个 sed:

s='"tree": "/a/anything-here/b/"'
sed -E 's~"(/[^/]*/)[^/]*/~\1new-string/~' <<< "$s"
"tree": /a/new-string/b/"

或者使用awk:

awk -v str='new-string' 'BEGIN{FS=OFS="/"} {$3 = str} 1' <<< "$s"
"tree": "/a/new-string/b/"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-27
    • 2013-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    相关资源
    最近更新 更多