Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ashishjullia/96e950368de1e7233197f1a5da000635 to your computer and use it in GitHub Desktop.
Save ashishjullia/96e950368de1e7233197f1a5da000635 to your computer and use it in GitHub Desktop.
Convert a private key to a single line using sed command line tool.
sed ':a;N;$!ba;s/\n/\\n/g' certificate_file_name_or_key_file_name | sed 's/^[ \t]*//;s/[ \t]*$//'

Let's break it down step by step.

1. sed ':a;N;$!ba;s/\n/\\n/g' certificate_file_name_or_key_file_name:

  • :a: Define a label called 'a'.
  • N: Append the next line of input to the current pattern space (with an embedded newline).
  • $!ba: If we're not at the last line ($!), then branch (go) to the label 'a'. This causes sed to loop, accumulating the entire file into the pattern space.
  • s/\n/\\n/g: Once the entire file is loaded into the pattern space, this substitution command is executed. It replaces every newline character (\n) with the string \n. The 'g' flag ensures all occurrences in the pattern space are replaced.

Essentially, this sed command reads the whole file into memory (into its pattern space) and replaces all newline characters with the string \n.

2. |:

This is a pipe. It takes the output of the command on its left (first sed command) and sends it as input to the command on its right (second sed command).

3. sed 's/^[ \t]*//;s/[ \t]*$//':

This sed command is actually two substitution commands separated by a semicolon.

  • s/^[ \t]*//: This command replaces any leading whitespaces (spaces or tabs) at the beginning of the string with nothing, effectively removing them.
  • s/[ \t]*$//: This command replaces any trailing whitespaces (spaces or tabs) at the end of the string with nothing, removing them.

The combination of these two commands ensures that any leading and trailing white spaces are removed.

In summary:

The given set of commands replaces every newline character in a file with the string \n and then strips off any leading or trailing white spaces from the resulting string.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment