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.

Top comments (0)