【问题标题】:How to loop through json and replace values with grep & sed in multiple files如何遍历json并在多个文件中用grep和sed替换值
【发布时间】:2018-09-22 09:13:06
【问题描述】:

我有一个名为 reference.json 的参考 json 文件,其中包含我想在 .html 文件中替换的键/值。

{
    "a.js": "first.1a.js",
    "b.js": "second.2b.js",
    "c.js": "third.3b.js"
}

然后我得到了 3 个不同的 html 文件

test1.html

<!DOCTYPE html>
<html lang="en">
<head>
  ..
<body>
  <div class="container">

    <h1>file 1</h1>

  </div>

  <script src="a.js"></script>
  <script src="b.js"></script>
  <script src="c.js"></script>
</body>
</html>

test2.html

<!DOCTYPE html>
<html lang="en">
<head>
  ...
</head>
<body>
  <div class="container">

    <h1>file 2</h1>

  </div>

  <script src="a.js"></script>
  <script src="b.js"></script>
  <script src="c.js"></script>
</body>
</html>

还有一个文件夹中的文件folder1/test3.html

<!DOCTYPE html>
<html lang="en">
<head>
  ...
<body>
  <div class="container">

    <h1>file 3</h1>

  </div>

  <script src="../js/a.js"></script>
  <script src="../js/b.js"></script>
  <script src="../js/c.js"></script>
</body>
</html>

如何搜索我的所有 .html 文件并使用 grep 和 sed 替换为我的 json 中的值?

【问题讨论】:

  • 展示你的尝试
  • 这里为什么要使用sed?使用 AWK 或其他工具更容易解决。此外,您的 test1.html 和 test2.html 几乎相同,因此在您的问题中包含这两个文件不会提供额外信息。

标签: sed terminal grep


【解决方案1】:

假设您的 reference.json 格式正确,这个单行代码将为您完成:

$ CMD=" sed -i $( cat reference.json | grep ":" | sed 's/ //g;s/,//g;s/"//g' | sed 's/:/\//g' | awk '{printf("s/%s/g;",$0)}' )" && find . -name "*.html" -exec ${CMD} {} \;

解释:

使用 reference.json 形成一个 sed 替换表达式以在 sed 命令中使用它。使用 find 命令查找所有“*.html”文件并执行替换。

如果reference.json没有格式化,可以使用如下命令格式化:

$ python -m json.tool reference.json

【讨论】:

    猜你喜欢
    • 2015-08-01
    • 2017-09-08
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 2014-12-15
    • 2018-01-10
    • 1970-01-01
    相关资源
    最近更新 更多