[英]Sed: modifying only some lines
In my /etc/apt/sources.list I want to append to all non-comment lines "contrib non-free" using sed.在我的 /etc/apt/sources.list 中,我想使用 sed 将“contrib non-free”附加到所有非注释行。
Here is my expression:这是我的表达:
sed -n -i '/^\([^#].*main\)/{s/main/main contrib non-free/p}' /etc/apt/sources.list
It does what I want but it also removes all other lines.它做我想要的,但它也删除了所有其他行。
What am I doing wrong?我究竟做错了什么?
Problem is with the option -n
in your command that suppresses normal output.问题在于您的命令中的选项
-n
会抑制正常输出。 You need to remove -n
and also remove p
option from substitution to avoid double printing of matching lines.您需要删除
-n
并从替换中删除p
选项以避免重复打印匹配行。
This command should work for you:这个命令应该对你有用:
sed -i '/^\([^#].*main\)/s/main/& contrib non-free/' /etc/apt/sources.list
The accepted answer from @anubhava (thanks for your code, as it pointed me in the right direction) would add contrib non-free even if it already exists in the line. @anubhava 接受的答案(感谢您的代码,因为它为我指明了正确的方向)会添加 contrib non-free,即使它已经存在于行中。 Try the following:
请尝试以下操作:
sed -i '/^\([^#].*main\)*$/s/main/& contrib non-free/' /etc/apt/sources.list
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.