Issue
I am using a bash shell and trying to process text file to replace line breaks with a single line string with "\n"s. Example:
Source file:
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
Desired Output
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
I tried many tr and sed examples here and cannot get it done. thanks.
Solution
Try this:
sed -e :a -e '$!N;s/\n/\\\n/;ta' file
With Gnu sed, you may need to escape new line only once:
sed -e :a -e '$!N;s/\n/\\n/;ta' file
All lines are joined and new line characters replaced with \\\n
.
You can add the -i
flag to edit the file in place or redirect output to a new file:
sed -e :a -e '$!N;s/\n/\\\n/;ta' file > newfile
Answered By - SLePort