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

how to use tr or sed to replace line breaks in a YAML file to single line string with '\n'

我正在使用 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 示例,但无法完成。谢谢。

试试这个:

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