79784964

Date: 2025-10-07 22:16:30
Score: 0.5
Natty:
Report link

This works in some linux distros bash - not verified in all

#### sed please note the "!"/ negation does not work properly in sed and it is recommended that "!" to be used followed by { group of commands }

#### 1 . sed comment out lines that contain a specific text (search_string) and are not empty

sed '/^$/! {/search_string/{ s/^#*/#/g; }}'

# /^$/! : negates empty lines -> This is an address that matches all lines that are not empty.

# ^$ : matches an empty line.

# ! : inverts the match, so it applies to non-empty lines.

# {/search_string/ { s/^#*/#/g; }}

# {...} : groups a set of commands to be executed on the lines selected by the preceding address.

# /search_string/ : replace only in the lines that contain "search_string"

# { s/^#*/#/g; } : { new set of commands }

# s/^#*/#/g; : search lines not starting with "#" and add "#" in the front of the line

#### 2 . sed comment out lines that do not contain a specific text (search_string) and are not empty

sed '/^$/! {/search_string/! { s/^#*/#/g; }}'

# /^$/! : negates empty lines -> This is an address that matches all lines that are not empty.

# ^$ : matches an empty line.

# ! : inverts the match, so it applies to non-empty lines.

# {/search_string/! { s/^#*/#/g; }}

# {...} : groups a set of commands to be executed on the lines selected by the preceding address.

# /search_string/! : negates the lines containing search_string - so replace only in the lines that do not contain "search_string"

# { s/^#*/#/g; } : { new set of commands }

# s/^#*/#/g; : search lines not starting with "#" and add "#" in the front of the line

Reasons:
  • Long answer (-1):
  • No code block (0.5):
  • Low reputation (1):
Posted by: Gabriel G