首页 > 解决方案 > 过滤输出并附加到一行内的文件

问题描述

我有以下输出:

{"success":true,"results":2,"total":2,"more":false,"offset":0,"hits":[{"path":"/content/dam/fr/fr-fr/frontend-testing/content-components","excerpt":"","name":"content-components","title":"Content Components","lastModified":"2019-05-16 16:01:29","created":"2020-08-19 05:13:27"},{"path":"/content/dam/ae/ae-ar/hidden/products","excerpt":"","name":"products","title":"products","created":"2020-08-19 05:14:44"}]}

我只需要过滤路径之后的部分:我成功地做到了”

e.g 
/content/dam/ae/ae-ar/hidden/products
and
/content/dam/ae/ae-ar/hidden/products

现在对我来说超级棘手的部分是我必须将此输出附加到内容为:

<?xml version="1.0" encoding="UTF-8"?>
<workspaceFilter version="1.0">
    <filter root="/apps/aem65-logistics-content-migration" mode="replace" />
    <filter root="/var/groovyconsole/scripts/aecu/logistics" mode="replace" />
     <filter root="****HERE IS WHERE THE output from the previous query must go****" mode="replace" />
</workspaceFilter>

因此,每次都应创建一个新行,其中包含来自查询的输出过滤器。不知道 bash 会如何发生。这就是我寻求帮助的原因。

我做了什么但到目前为止没有工作:

sed '' "/<workspaceFilter version="1.0">/a \<filter root="$OUTPUT" mode="replace" > " filter.xml

但新行也需要与其他“根”在同一行,我得到

sed: />/>/a \<filter root="/content/dhl/fr/fr-fr/frontend-testing/content-components": No such file or directory
sed: "/content/dhl/ae/ae-ar/hidden/products" mode="replace" > : No such file or directory
<?xml version="1.0" encoding="UTF-8"?>
<workspaceFilter version="1.0">
    <filter root="/apps/aem65-logistics-content-migration" mode="replace" />
    <filter root="/var/groovyconsole/scripts/aecu/logistics" mode="replace" />
</workspaceFilter

标签: linuxbashshell

解决方案


您可以为它使用两个命令jq和 awk。第一个帮助您过滤json文件的内容,然后您可以使用awk逐行分析以生成xml内容

$ jq .hits[].path a.out | awk '{print \
  "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \
   <workspaceFilter version=\"1.0\"> \
      <filter root=\"/apps/aem65-logistics-content-migration\" mode=\"replace\" /> \
      <filter root=\"/var/groovyconsole/scripts/aecu/logistics\" mode=\"replace\" /> \
      <filter root="$1" mode=\"replace\" /> \
   </workspaceFilter> \
  "}'

其中 a.out 是您拥有的 json 内容:

{
 "success": true,
 "results": 2,
 "total": 2,
 "more": false,
 "offset": 0,
 "hits": [
   {
    "path": "/content/dam/fr/fr-fr/frontend-testing/content-components",
    "excerpt": "",
    "name": "content-components",
    "title": "Content Components",
    "lastModified": "2019-05-16 16:01:29",
    "created": "2020-08-19 05:13:27"
   },
   {
    "path": "/content/dam/ae/ae-ar/hidden/products",
    "excerpt": "",
    "name": "products",
    "title": "products",
    "created": "2020-08-19 05:14:44"
   }
 ]
}

推荐阅读