如何使用tr或sed将YAML文件中的换行符替换为带有'\ n'的单行字符串

时间:2019-02-06 06:50:51

标签: sed tr

我正在使用bash shell,并尝试处理文本文件以将换行符替换为带有“ \ n”的单个行字符串。示例:

源文件:

apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: LOOOONG-STRING
    server: https://1.2.3.4:8443
  name: cluster-name
contexts:
- context:
    cluster: cluster-name
    user: cluster-admin
  name: cluster-admin@cluster-name
current-context: cluster-admin@cluster-name
kind: Config
preferences: {}
users:
- name: cluster-admin
  user:
    client-certificate-data: LOOOONG-STRING
    client-key-data: LOOOONG-STRING

所需的输出

apiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: LOOOONG-STRING\n    server: https://1.2.3.4:8443\n  name: cluster-name\ncontexts:\n- context:\n    cluster: cluster-name\n    user: cluster-admin\n  name: cluster-admin@cluster-name\ncurrent-context: cluster-admin@cluster-name\nkind: Config\npreferences: {}\nusers:\n- name: cluster-admin\n  user:\n    client-certificate-data: LOOOONG-STRING\n    client-key-data: LOOOONG-STRING

我在这里尝试了许多tr和sed示例,但无法完成。谢谢。

1 个答案:

答案 0 :(得分:0)

尝试一下:

sed -e :a -e '$!N;s/\n/\\\n/;ta' file

使用Gnu sed,您可能只需要转义一次新行:

sed -e :a -e '$!N;s/\n/\\n/;ta' file

所有行都合并,新行字符替换为\\\n

您可以添加-i标志以在适当位置编辑文件或将输出重定向到新文件:

sed -e :a -e '$!N;s/\n/\\\n/;ta' file > newfile