bash Sed 错误:替换表达式中的错误选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30050923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:56:10  来源:igfitidea点击:

Sed error : bad option in substitution expression

linuxbashshellsed

提问by ogs

I have a configuration file (gpsd.default) containing data with the following format:

我有一个gpsd.default包含以下格式数据的配置文件 ( ):

# If you must specify a non-NMEA driver, uncomment and modify the next line     
GPSD_SOCKET="/var/run/gpsd.sock"                                                
GPSD_OPTIONS=""                                                                
GPS_DEVICES="" 

I am making a change on the file with sed:

我正在使用 sed 对文件进行更改:

sed -i 's/^GPS_DEVICES="".*/GPS_DEVICES="dev/ttyUSB1"/' /etc/default/gpsd.default
or 
sed -i '4s/^.*/GPS_DEVICES="dev/ttyUSB1"/' /etc/default/gpsd.default

The above sedcommand returns error:

上面的sed命令返回错误:

sed: bad option in substitution expression

sed:替换表达式中的错误选项

Because the new line contains "/" in its expression.

因为新行在/其表达式中包含“ ”。

How to update my sedcommand to make it work?

如何更新我的sed命令以使其工作?

回答by fedorqui 'SO stop harming'

This is because you are using a regex containing /, which is the same character seduses as delimiter.

这是因为您使用的是包含 的正则表达式/,它与sed用作分隔符的字符相同。

Just change the seddelimiter to another one, for example ~:

只需将sed分隔符更改为另一个,例如~

sed -i 's~^GPS_DEVICES="".*~GPS_DEVICES="dev/ttyUSB1"~' /etc/default/gpsd.default

By the way, since you are changing files in /etc, you may want to use -i.bak, so that the original file gets backed up. It is a good practice to prevent loss of important information.

顺便说一下,由于您正在更改 中的文件/etc,您可能需要使用-i.bak,以便备份原始文件。防止丢失重要信息是一种很好的做法。

回答by Harshad Yeola

You should update your sed command to this.

您应该将您的 sed 命令更新为此。

sed -i 's/^GPS_DEVICES=\"\".*/GPS_DEVICES=\"dev\/ttyUSB1\"/' /etc/default/gpsd.default