DEV Community

abbazs
abbazs

Posted on

A One-Liner `sed` Command to Format SSH Config File

SED Command

sed -i -e '/^\s*#/!{/^\s*Host /!s/^\s*/\t/}' \
    -e '/^\s*Host /s/^\s*//' \
    ~/.ssh/config
Enter fullscreen mode Exit fullscreen mode

With backup of old config file having extension .old

sed -i.old -e '/^\s*#/!{/^\s*Host /!s/^\s*/\t/}' \
    -e '/^\s*Host /s/^\s*//' \
    ~/.ssh/config
Enter fullscreen mode Exit fullscreen mode

Breakdown

  • Skip Commented Lines:
    • Ignores lines starting with #, possibly preceded by whitespace.
  /^\s*#/!{}
Enter fullscreen mode Exit fullscreen mode
  • Indent Non-Host and Non-Comment Lines:
  {/^\s*Host /!s/^\s*/\t/}
Enter fullscreen mode Exit fullscreen mode
  • Matches lines that do not start with Host.
  /^\s*Host /!
Enter fullscreen mode Exit fullscreen mode
  • Replaces leading spaces or tabs with a single tab.
  s/^\s*/\t/
Enter fullscreen mode Exit fullscreen mode
  • Remove Leading Spaces from Host Lines:
  -e '/^\s*Host /s/^\s*//'
Enter fullscreen mode Exit fullscreen mode
  • Matches lines that start with Host.
  /^\s*Host /
Enter fullscreen mode Exit fullscreen mode
  • Removes all leading spaces or tabs from those lines.
  s/^\s*//
Enter fullscreen mode Exit fullscreen mode

Example

Input:

Host myserver
HostName ssh.example.com
User myuser
 Port 22
 IdentityFile ~/.ssh/mykey

   Host another-server
    HostName another.example.com
   User anotheruser
Port 2022
IdentityFile ~/.ssh/anotherkey
Enter fullscreen mode Exit fullscreen mode

Output:

Host myserver
    HostName ssh.example.com
    User myuser
    Port 22
    IdentityFile ~/.ssh/mykey

Host another-server
    HostName another.example.com
    User anotheruser
    Port 2022
    IdentityFile ~/.ssh/anotherkey
Enter fullscreen mode Exit fullscreen mode

This formats the file in place (-i flag), ensuring consistent indentation and removing leading spaces.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs