Comment And Uncomment All Lines in a Linux File with Sed
Just a couple of sed one-liners for adding and removing comments in the form of # marks (in the case of my ~/.ssh/config file). Both of these are safe to run repeatedly (you won’t end up with multiple # marks or anything).
- * First adding comments, which means a “#” mark at the start of every line
sed -i '' 's/^\([^#]\)/#\1/g' ~/.ssh/config
- Second removing the comments, just stripping out the “#” marks.
sed -i '' 's/^#//g' ~/.ssh/config
- The “-i” flag means “edit in place” and requires an extra argument for the backup file’s extension. I’ve given an empty string so that no backup is made
- sed requires escaping of capturing parentheses, hence the \( and \) in the first example
- The final ‘g’ at the end of the expressions means “global”, i.e. replace all occurrences