我有一个bash脚本,需要注释掉文件中的第一个非注释行并显示它,如下所示:
env=$(grep -v -m 1 "#" file)
if [ "$env" != "" ]
then
sed -i "/\<$env\>/s/^/#/" file
fi
echo $env
这就变成了:
#this is an example file
this is the first line
this is the second line
变成这个:
#this is an example file
#this is the first line
this is the second line
并与此相呼应 this is the first line
我相信,有一种更简单,规范的方法可以做到这一点,也许只使用sed即可。使其成为单行代码会很方便,因为它实际上是通过ssh执行的。另一方面,通过ssh执行会导致在sed参数中扩展环境变量的问题,并且使用sscape进行转义是\\\$env
行不通的。任何建议,我们将不胜感激。
正如您已经建议的那样,您只能使用sed
:
sed '0,/^[^#]/ s/^[^#].*/#\0/' file.txt
上面的sed命令适用于从文件的第一行到第一个未注释的行的范围。在此范围内,它将用替换未注释行的开头#
。因为该范围仅适用于第一条未注释的行,所以仅此行将被注释。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句