简体   繁体   English

多行正则表达式外壳脚本

[英]Multiline regular expression shell script

I need to replace a hash for a file in manifest. 我需要替换清单中文件的哈希。 My problem is I don't know the original hash, only the new one. 我的问题是我不知道原始哈希,只有新哈希。

mainfest : 主要

[
  {
    "file": "bundle.js",
    "hash": "0a4c61f0cf23ca1fd39c411140941cd5"
  },
  {
    "file": "0fdbe5712e250dac1fa5930395f65a27.jpg",
    "hash": "0fdbe5712e250dac1fa5930395f65a27"
  }
]

As you could see, in the manifest (JSON) file name and hash are bundled in an object. 如您所见,清单文件(JSON)中的文件名和哈希值捆绑在一个对象中。

I want to change the hash file for the bundle.js with a new one. 我想用一个新的更改bundle.js的哈希文件。 I use below shell script with sed and regular expression to replace the hash. 我在下面的shell脚本中使用sed和正则表达式替换哈希。

shell script: 外壳脚本:

#!/bin/sh
NEW_HASH="$(md5 < ./scripts/bundle.js)"
sed 's/\({"file": "bundle.js","hash": "\).*\("}\)/\1'$NEW_HASH'\2/g' chcp.manifest

Only I don't know how to match the multiple lines. 只有我不知道如何匹配多行。 Mine regex matches only a single line 我的正则表达式仅匹配一行

{"file": "bundle.js","hash": "0a4c61f0cf23ca1fd39c411140941cd5"}

and not 并不是

{
   "file": "bundle.js",
   "hash": "0a4c61f0cf23ca1fd39c411140941cd5"
 }

I tried something like: 我尝试了类似的东西:

sed 's/\({"file": "bundle.js",\n   "hash": "\).*\("\n   }\)/\1'$NEW_HASH'\2/g' chcp.manifest

but \\n doesn't seam to work for matching a new line 但是\\ n不能用于匹配新行

Trying to parse a structured format like JSON (or XML, etc) with something like sed or awk is tricky and never as robust as using a tool actually designed to parse the data with which you're working. 尝试使用sedawk类的语法分析诸如JSON(或XML等)之类的结构化格式是一件棘手的事情,并且永远不会像使用实际设计用来解析正在使用的数据的工具那样强大。

Your task would be relatively trivial using Python or Ruby or Perl or something else with a JSON parser. 使用Python或Ruby或Perl或其他带有JSON解析器的工具,您的任务将相对琐碎。 For shell scripts, you may want to investigate the jq command, which is available as a package for most distributions. 对于shell脚本,您可能需要研究jq命令,该命令可作为大多数发行版的软件包使用。

Using jq , you could use the technique described in this document , which would boil down to: 使用jq ,您可以使用本文档中描述的技术,该技术可以归结为:

NEW_HASH="$(md5 < ./scripts/bundle.js)"
jq 'map(if .file == "bundle.json" 
        then . + {"hash": "'"$NEW_HASH"'"}
        else . 
        end)' chcp.manifest

That would generate the new document on stdout ; 这将在stdout上生成新文档; you could obviously save that to a file and then rename that to replace the original. 您显然可以将其保存到文件中,然后重命名以替换原始文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM