How to Fix “sed unknown option to ‘s’”?

The “sed” command is used to find and replace a string, delete/print a line or line number, and insert anything before the line number. When searching a string that contains forward slashes in its name, the sed tool throws an error, i.e., “sed unknown option to s”. The error occurs because the sed utility cannot differentiate between the slashes in its syntax and the slashes in the string. 

This post will address the possible reason and solution of the error “sed unknown option to s”. 

Reason: Searching a String/Pattern Containing Slashes (Too Many Slashes)

The following command tries to search the pattern “Linux” and replace it with pattern “a/kali”. However, the “sed” command throws the error while searching: 

$ sed -e "s/Linux/a/kali/" FirstFile.txt

In the above command, the “s” denotes the “substitution” operation. Whereas the “/” specifies the  delimiters that also take the forward slash in the pattern “ a/kali” as a delimiter, that’s why the error generates, i.e., “unknown option to ‘s‘ ”.

Solution: Use New Delimiter “|” or “%”

The solution to resolve this error is that use the character “|(Pipe)” as a new “delimiter” in place of “slashes”. It will not print in the output as shown in the below image:

$ sed -e "s|Linux|a/kali|" FirstFile.txt

The string “Linux” has been successfully replaced in the “FirstFile.txt” to the “a/kali” without showing the error.

Alternative Solution: Use “%” Delimiter 

The user can also use the “%(percentage)” character in place of “|(Pipe)”. It will also work and replace the specified string:

$ sed -e "s%Linux%a/kali%" FirstFile.txt

The above command has done its job without any error “unknown option to ‘s’ ” of the “sed” command.

Conclusion

The error “sed unknown option to s” occurs due to the “too many slashes” in the “sed” command syntax. It takes every “/(forward slash)” placed in the string as a delimiter. To fix this error, use the  “|(Pipe)” or  “%(percentage)” as a new delimiter in the “sed” command syntax. This post has illustrated the possible reasons and solutions to the error “sed unknown option to s” in detail.