【问题标题】:How to use 'tr' to find and replace only ---如何使用 'tr' 仅查找和替换 ---
【发布时间】:2019-09-03 08:49:52
【问题描述】:

所以,我有一个命令 (kustomize build) 的输出,我想将输出中的 --- 转换为 ###。例如:

$ kustomize build
apiVersion: extensions/v1
kind: Ingress
metadata: 
  labels:
    app: hello-world
---
apiVersion: v1
kind: Service
metadata:
  name: hello-world
spec:
  ports:
  - name: service
    port: 443
    targetPort: 8443
  selector:
    app: hello-world
  type: NodePort

我想把它改成:

apiVersion: extensions/v1
kind: Ingress
metadata: 
  labels:
    app: hello-world
###
apiVersion: v1
kind: Service
metadata:
  name: hello-world
spec:
  ports:
  - name: service
    port: 443
    targetPort: 8443
  selector:
    app: hello-world
  type: NodePort

我尝试了$ kustomize build | tr '\---' '#',但这会将单个'-' 的每个实例替换为'#'。我什至尝试过tr '[-]{3}' '#',但即便如此也无济于事。我该怎么做?

【问题讨论】:

  • tr 只是一个错误的工具
  • 为什么要移除标准的 YAML 文档标记并替换为注释?
  • 其实,我现在想办法解决这个问题 :)

标签: bash tr kustomize


【解决方案1】:

tr 只翻译单个字符(并删除它们,如果你指定的话)。

您需要使用的是可以替换字符组的“流编辑器”sed

sed 's/---/###/g'

【讨论】:

  • 根据------是否应该替换为######,可能与使用sed 's/^---$/###/g'有关
  • @mouviciel 更重要的是,裸字符串--- 可能出现在文档标记以外的许多上下文中。
  • (即使那样,^---$ 也可以匹配多行字符串中的一行。简单地说,sed 通常无法真正胜任编辑 YAML 的任务。)
  • @chepner OP 从未指定输入是 YAML ;-)
猜你喜欢
  • 2012-01-11
  • 2014-09-01
  • 2013-11-19
  • 1970-01-01
  • 2021-04-16
  • 2011-05-26
  • 1970-01-01
  • 1970-01-01
  • 2012-09-22
相关资源
最近更新 更多