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.

Please leave your appreciation by commenting on this post!

I can do that

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

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay